Trouble using Ray.Intersect method on bounding boxes in a 2D XNA game

Posted by getsauce on Game Development See other posts from Game Development or by getsauce
Published on 2013-05-30T00:22:11Z Indexed on 2013/11/02 4:11 UTC
Read the original article Hit count: 239

Filed under:
|

I am trying to use a ray and bounding box to determine if a box is between the player and the mouse pointer in 2D space. When I try testing the code, the collision will return true when pointed at the box but it also returns true under other circumstances where it shouldn't.

For instance. If I have a player on the left and a box directly to the right, I can put the mouse pointer a few hundred pixels above the box or a few hundred below and it will still return true. Also, I can put my mouse pointer to the left of the player and in a certain area it will still return true. Does anyone have any idea what might cause this?

I have left out definitions for some of my members and properties just to make this code sample easier to read. The position property is just a Vector2 for where each object is located.

ray = new Ray(new Vector3(player.Position, 0), new Vector3(mouse.Position, 0);
box = new BoundingBox(new Vector3(box.Position, 0), new Vector3(
new Vector2(box.Position + box.Width, box.Position + box.Height), 0);

if (ray.Intersects(box) != null)
    collision = true;
else
    collision = false;

© Game Development or respective owner

Related posts about XNA

Related posts about c#