How to use setUserPointer/getUserPointer for collision detections with Ammo.js

I want to print names of colliding objects. I made a very simple example.

I created an object to keep a user data:

``        const userData = { name: name }; ``

I keep this object in a body using setUserPointer:

``body.setUserPointer(userData); ``

I try to get this names using getUserPointer and print them. But I get "undefined" instead of names:

``function detectCollison(): void {     const dispatcher = physicsWorld.getDispatcher();     const numManifolds = dispatcher.getNumManifolds();      for (let i = 0; i < numManifolds; i++)     {         const contactManifold = dispatcher.getManifoldByIndexInternal(i);         const body0 = contactManifold.getBody0();         const body1 = contactManifold.getBody1();          const p0 = body0.getUserPointer();         const p1 = body1.getUserPointer();          console.log("first object: " + p0.name);         console.log("second object: " + p1.name);     } } ``

This is a TypeScript version. I tried to keep names as a body property but it does not work too. It prints "undefined" instead of names:

``        (this.body as any).name = name;          physicsWorld.addRigidBody(this.body); ``
``function detectCollison(): void {     const dispatcher = physicsWorld.getDispatcher();     const numManifolds = dispatcher.getNumManifolds();      for (let i = 0; i < numManifolds; i++)     {         const contactManifold = dispatcher.getManifoldByIndexInternal(i);         const body0 = contactManifold.getBody0();         const body1 = contactManifold.getBody1();          console.log("first object: " + (body0 as any).name);         console.log("second object: " + (body1 as any).name);     } } $$```$$ ``

Why raycast is ignorring collision with certain parts of an object?

I have a simple script attached to the player that makes it stay at an equal distance from the ground always.

``void Update() {     RaycastHit hit;     if (Physics.Raycast(transform.position, Vector3.down, out hit))     {         transform.position = new Vector3(hit.point.x, hit.point.y + offset, hit.point.z);     } } ``

But for some reason it ignores collision as you can see here: https://youtu.be/8X0pw5tkjpE

How can I get rid of this problem?

Is a target pushed into a wall by a spell effect subject to collision damage?

Some spells can push the target X feet away (like thunderwave, which pushes 10 feet away on a failed save). I was wondering what happens if the target, while being pushed, encounters a wall or other rigid object. Does it take (bludgeoning) damage? To me it seems logical that it would: it is like falling, sudden force applied to a creature due to encountering resistance from an object.

Another not working 2D collision system

As many before me, I’m trying to make a 2D platformer. The current problem is the collision system. I tried to be smart and use sweeping and line segments to implement this, which ended up somewhat working, but not quite.

Here’s what I’m trying to do:

1. The player is made of four vertices
2. The map is made of axis-aligned line segments creating polygons
3. Calculate the next frame’s position of all four points
4. Create four line segments from the before/after positions, one for each vert
5. Intersect these segments with the map
6. Move the player to the collision point on the axis perpendicular to the wall only

Here’s what happens:

1. Some walls work just fine
2. Some walls have collision from the "wrong" side
3. Some walls have no collision
4. Some walls stop having collisions when sliding on them
5. Some walls can’t be moved away from

Here’s the relevant excerpts of my code. Subject to be refactored, I wanted to get this working first.

``// Player public class Player extends Sprite {      private PlayScreen scr;      public Vector2 vel;     public Vector2 lastMove;      public Vector2[] verts = new Vector2[2];           public Player(PlayScreen s, float x, float y) {         this.scr = s;         this.setPosition(x, y);         this.setSize(8, 16);         vel = new Vector2(0, 0);         lastMove = new Vector2(0, 0);                  Rectangle r = this.getBoundingRectangle();         float x1 = r.x;         float x2 = r.x + r.width;         float y1 = r.y;          float y2 = r.y + r.height;                  verts[0] = new Vector2(x1,y1);         verts[1] = new Vector2(x2,y2);     }      public void update(float delta) {         float xpos = this.getX();         float ypos = this.getY();          float dx = vel.x * delta;         float dy = vel.y * delta;          this.setPosition(xpos + dx, ypos + dy);         this.lastMove.set(dx, dy);     }      public Vector2 getTR() {         return new Vector2(this.getVertices()[Batch.X3],this.getVertices()[Batch.Y3]);     }      public Vector2 getBR() {         return new Vector2(this.getVertices()[Batch.X4],this.getVertices()[Batch.Y4]);     }          public Vector2 getTL() {         return new Vector2(this.getVertices()[Batch.X2],this.getVertices()[Batch.Y2]);     }          public Vector2 getBL() {         return new Vector2(this.getVertices()[Batch.X1],this.getVertices()[Batch.Y1]);     }      } ``
``// PlayScreen public class PlayScreen implements Screen {      private OrthogonalTiledMapRenderer renderer;     private Player player;     private Collision collision;      public PlayScreen(MovementGame mg) {                  // omitted cam/viewport setup         // omitted map loading         this.renderer = new OrthogonalTiledMapRenderer(map, 1);         cam.position.set(viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2, 0);          player = new Player(this, -50, -50);         collision = new Collision();          for (PolygonMapObject obj : this.map.getLayers().get(2).getObjects().getByType(PolygonMapObject.class)) {             collision.addObj(obj);         }     }      @Override     public void render(float delta) {         Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);          player.vel.x = 0;         player.vel.y = 0;          // omitted input handling. sets player.vel to +-100 x/y on arrow key press          player.update(delta);          // omitted debug player drawing         // omitted debug player drawing for next position          collision.doCollision(player, cam);         cam.position.lerp(new Vector3(player.getX(), player.getY(), 0),1f);          cam.update();         renderer.setView(cam);          // omitted debug map drawing     } }  ``
``public class Collision {      public ArrayList<Vector2[]> lines;      public Collision() {         lines = new ArrayList<>();     }      // convert polygon verts to lines and add to list     public void addObj(PolygonMapObject obj) {         float[] a = obj.getPolygon().getTransformedVertices();         ArrayList<Vector2> verts = new ArrayList<>();         for (int i = 0; i < obj.getPolygon().getVertices().length; i += 2) {             verts.add(new Vector2(a[i + 0], a[i + 1]));         }          for (int i = 0; i < verts.size() - 1; i++) {             lines.add(new Vector2[] { verts.get(i), verts.get(i + 1) });         }         lines.add(new Vector2[] { verts.get(0), verts.get(verts.size() - 1) });     }      // detect and resolve collision. camera is for debug drawing     public void doCollision(Player p, Camera cam) {         Vector2 col;         float dx = 0;         float dy = 0;         // try to intersect with every line         for (Vector2[] line : lines) {             dx = dy = 0;             // create the movement line for each vert of the player              // try to intersect it with the currect line             // there HAS to be a better way...             if ((col = getLineIntersection(p.getBL(), p.getBL().sub(p.lastMove), line[0], line[1])) != null) {                 dx = p.getBL().x - col.x;                 dy = p.getBL().y - col.y;             }             if ((col = getLineIntersection(p.getTL(), p.getTL().sub(p.lastMove), line[0], line[1])) != null) {                 dx = p.getTL().x - col.x;                 dy = p.getTL().y - col.y;             }             if ((col = getLineIntersection(p.getBR(), p.getBR().sub(p.lastMove), line[0], line[1])) != null) {                 dx = p.getBR().x - col.x;                 dy = p.getBR().y - col.y;             }             if ((col = getLineIntersection(p.getTR(), p.getTR().sub(p.lastMove), line[0], line[1])) != null) {                 dx = p.getTR().x - col.x;                 dy = p.getTR().y - col.y;             }             // something collided. resolve             if (col != null) {                                  if (line[0].y == line[1].y) {                 // line is horizontal. push player up/down only                     p.vel.x = 0;                     dx = 0;                 } else {                 // line is vertical. push player left/right only                     p.vel.y=0;                     dy = 0;                 }                  // omitted debug drawing                 // finally, update the player pos                 p.setPosition(p.getX() - dx, p.getY() - dy);             }         }     }      private Vector2 getLineIntersection(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3) {         Vector2 res = new Vector2();         if (Intersector.intersectSegments(p0, p1, p2, p3, res)) {             return res;         } else {             return null;         }     } } ``

Any ideas or tips on how this could be turned into something working? Or should I give up on this and do grid AABB-collision instead?

Finally, here’s a rare screenshot of the code doing what it should. Blue is the player’s position before the movement, red the intended position, yellow the resolved position and white the distance the player moved too far.

Same colors, but issue #5. The collision gets resolved onto the wall instead of away.

Thank you in advance for your help! Please excuse the form of this question, this is making me lose my mind…

How do you use custom collision on a skeletal mesh in UE4?

I have a vehicle rig that is a skeletal mesh that imports fine in to unreal but I was wondering how to use a mesh for collision on it. Normally you can just name the collision mesh with UCX_ in front of the name to do it but with skeletal meshes it makes you use a system called phat and I only see cubes/spheres/capsules for collision with that.

Collision Detection without Coordinates in Tilemaps in Pygame

So if I wan’t to make a collision detection with rectangles, than I can just do this as I have the coordinates of the rectangle:

``rcx = 200 rcy = 200 rcw = 200 rch = 100 plx = 500 ply = 450 plw = 50 plh = 50 rectcolor = (100, 150, 200)  testobj = pygame.draw.rect(win, rectcolor, (rcx, rcy, rcw, rch)) player = pygame.draw.rect(win, (150, 200, 100), (plx, ply, plw, plh))     if plx <= rcx + rcw and plx + plw >= rcx and ply <= rcy + rch and ply + plh >= rcy:     rectcolor = (50, 100, 50) else:     rectcolor = (100, 150, 200) ``

Ok, good! I made a collision detection with rectangles because I know the coordinates of the rectangles. (I don’t think this is the most efficient way but it works) Anyways I am programming a Bomberman game, right now I don’t have any sprites but I use rectangles for it. This is my code:

``import pygame  pygame.init()  WinWidth = 800 WinHeight = 608 p1x = 32 p1y = 32 vel = 1 clock = pygame.time.Clock()  win = pygame.display.set_mode((WinWidth, WinHeight))  def player():     pygame.draw.rect(win, (0, 200, 200), (p1x, p1y, 32, 32))  class invi:     def __init__(self, x, y):         self.x = x         self.y = y         pygame.draw.rect(win, (0, 255, 200), (x, y, 32, 32))   class Wall:     def __init__(self, x, y):         self.x = x         self.y = y         pygame.draw.rect(win, (50, 50, 50), (x, y, 32, 32))   class Breakable:     def __init__(self, x, y):         self.x = x         self.y = y         pygame.draw.rect(win, (200, 150, 100), (x, y, 32, 32))   game_map1 = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],              [0, 10, 10, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 10, 10, 0],              [0, 10, 0, 2, 0, 2, 0, 2, 0, 0, 0, 2, 0, 2, 0, 2, 0, 10, 0],              [0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0],              [0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0],              [0, 2, 2, 2, 2, 10, 10, 2, 2, 10, 2, 2, 10, 10, 2, 2, 2, 2, 0],              [0, 2, 0, 2, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 2, 0, 2, 0],              [0, 2, 2, 2, 2, 2, 0, 2, 2, 10, 2, 2, 0, 2, 2, 2, 2, 2, 0],              [0, 2, 0, 2, 0, 2, 0, 2, 10, 10, 10, 2, 0, 2, 0, 2, 0, 2, 0],              [0, 0, 0, 2, 2, 10, 10, 10, 10, 10, 10, 10, 10, 10, 2, 2, 0, 0, 0],              [0, 2, 0, 2, 0, 2, 0, 2, 10, 10, 10, 2, 0, 2, 0, 2, 0, 2, 0],              [0, 2, 2, 2, 2, 2, 0, 2, 2, 10, 2, 2, 0, 2, 2, 2, 2, 2, 0],              [0, 2, 0, 2, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 2, 0, 2, 0],              [0, 2, 2, 2, 2, 10, 10, 2, 2, 10, 2, 2, 10, 10, 2, 2, 2, 2, 0],              [0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0],              [0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0],              [0, 10, 0, 2, 0, 2, 0, 2, 0, 0, 0, 2, 0, 2, 0, 2, 0, 10, 0],              [0, 10, 10, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 10, 10, 0],              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]  run = True while run:      pygame.init()      clock.tick(100)     win.fill((0, 255, 200))     y = 0     for layer in game_map1:         x = 0         for tile in layer:             if tile == 0:                 Wall(x * 32, y * 32)             if tile == 10:                 invi(x * 32, y * 32)             if tile == 2:                 Breakable(x * 32, y * 32)             x += 1         y += 1      player()      for event in pygame.event.get():         if event.type == pygame.QUIT:             pygame.quit()             run = False     if event.type == pygame.KEYDOWN:         if event.key == pygame.K_d:             p1x += vel         elif event.key == pygame.K_a:             p1x -= vel      pygame.display.update() ``

sooo… I watched a tutorial and even tried to make a collision detection on my own. But I just can’t do it. I don’t have coordinates for the rectangles in the tilemap and there are very much rectangles in the tilemap, too. How could you make a collision detection with a tilemap with no coordinates and many rectangles? And yeah, the game doesn’t have much stuff going un ’til now… oh and I deleted the parts where I tried to make a collision detection as they all were bad, didn’t work, took up much of the place and just made the whole code more confusing.

Btw if this is not a good question to ask in this StackExchange Q&A Website, sorry, im new to this Website. But I would still be happy to get an answer on this question! 🙂

How to do collision detection in Unity between Character Controller, Rigidbody Collider and a NavmeshAgent?

I would like to know more about how collision detection works in Unity especially when character controllers and NavmeshAgents get involved.

For example, how can I detect collision between NavmeshAgent and a CharacterController? I have added a sphere collider to my NavmeshAgent, but it doesn’t seem to detect a collision unless I set it to “IsTrigger”. I have tried OnCollisionEnter(), OnControllerColliderHit() and OnTriggerEnter(). OnTriggerEnter() seems to be the only one that works and only when I enable “IsTrigger”.

How come the other two don’t work? Shouldn’t they? What if I didn’t want to make the collider a trigger?

Ray casting through terrain mesh + Octree ( Mesh collision )

I’m currently in development of a terrain editor which i will use for my game. One thing that is partially stopping my development is that I don’t have collision detection implemented between mouse ray cast and the terrain mesh.

The terrain is consisted of triangles and can be lowered and raised.Also the x and y values of the mesh don’t change. Of course what i need to do is ray cast through my mouse positions and get intersected triangle. I would get the point on the triangle using Barycentric coordinates. Just I’m not quite sure how does octree come into play here. As far as I understand it it works like a 3d quadtree, splitting the box into smaller box that the ray intersects. But which box do i choose ? How do i know which box is the closest one to the terrain, if either raised or lowered terrain ? How many subdivisions would i have? I was thinking on having as much as i have tiles( basically the last level of subdivisions would correspond to a x^3 box).

Right now i’m just doing collision with the 0 Z-value plane, and it works okay, but if the terrain is a bit raised then this can give faulty results.

Other two methods that i found is to iterate through the mesh, which of course is insanely inefficient; the other is to project the terrain in reverse and then i guess do some checking with the mouse coordinates (think it’s called z-buffer checking or something).

If anyone has any other ideas i’m all ears. Just note that the algorithm should be an efficient one (of course this depends on the implementation) and accurate.

Thanks !

Theoretical question about Zobrist hashing and chances of collision with slight modification

I’m using zobrist hashing, but for certain positions I want to put them in the cache but make them unique. This is what I’m doing:

``quint64 hash = position.zobristHash(); if (makeItUnique)     hash ^= reinterpret_cast<quint64>(this); ``

Is there any reason to suppose that what I’m doing will increase the likelihood of hash collisions?

Rolling on collision

I’m having a small issue where if I collide with another object (let’s use a simple cube) with my player (this player is just a sphere), the ball will infinitely roll in the opposite direction and WILL NOT STOP. my code is as follows:

``using UnityEngine;  public class PlayerController : MonoBehaviour {     private Rigidbody rb;     private float moveHorizontal;     private float moveVertical;      public float moveSpeed;         // Start is called before the first frame update     private void Awake()     {         rb = GetComponent<Rigidbody>();     }      // Update is called once per frame     void Update()     {         moveHorizontal = Input.GetAxis("Horizontal");         moveVertical = Input.GetAxis("Vertical");     }      private void FixedUpdate()     {         MovePlayer();             }      private void MovePlayer()     {         Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);         rb.AddForce(movement * moveSpeed);     } ``

I even changed the ForceMode to ForceMode.Impulse so be able to see what it was doing a little easier, and it is in fact slowly rolling away infinitely with no way to stop it.

Both objects have a Rigidbody for them to be able to react to being hit. This is my first time messing with 3d. I tried to do something like this to make it not roll away on impact

``private void OnCollisionExit(Collision collision)     {         if (collision.collider.gameObject.layer != LayerMask.NameToLayer("Ground"))         {             rb.velocity = Vector3.zero;         }     } ``

But then if I want to jump on the cube (lets say the cube is an enemy and I’m jumping on it to kill it), then it acts very wonky each time it touches the edge of the cube and I haven’t made it on top (again, because the velocity is being set to zero). I am all out of ideas and would love some input here!

EDIT: I now realize that the ball will slowly roll forever even without collision and just simply moving. I am very lost !