I'm checking to see if the ray that I've created is intersecting with a rectangle. I'm using the boundingbox class to pass the rectangle into the intersect method in the Ray class, but unfortunately it isn't working I'm wondering if it has something to do with how I constructed either the boundingbox or the Ray.

The code is below, any help with this would be great.

  Ray bulletRay = new Ray(new Vector3(lensPosition, 0.0f), (new Vector3(lensPosition, 0.0f) - new Vector3(level.Player.Position.X, level.Player.Position.Y - 32.0f, 0.0f)));

Rectangle tileBounds = Level.GetBounds(x, y);
                        BoundingBox box = new BoundingBox(
                        new Vector3(tileBounds.Left, tileBounds.Top, 0), // Front = 0
                        new Vector3(tileBounds.Right, tileBounds.Bottom, 0)); // Back = 0

                        float? output;

                        bulletRay.Intersects(ref box,out output);
                        if (output.HasValue)
                          wallInWay = true;
  • \$\begingroup\$ Should the ray be pointing straight down? (It's vertical.) \$\endgroup\$
    – Olhovsky
    Jun 1, 2011 at 20:33
  • \$\begingroup\$ The Ray should be should be pointing anywhere from down and right to down and left depending on where the character is \$\endgroup\$
    – dbomb101
    Jun 1, 2011 at 20:53
  • \$\begingroup\$ "I'm checking to see if I've created is intersecting with a rectangle." ...What? \$\endgroup\$ Jun 1, 2011 at 22:09
  • \$\begingroup\$ Fixed that typo for you AttackingHobo -- he meant "...if the ray I've created is...". \$\endgroup\$
    – Olhovsky
    Jun 1, 2011 at 22:10

1 Answer 1


Here is a refactoring of your code (this does the exact same thing as what you posted in your question, I just wrote it a little differently):

Vector3 rayStart = new Vector3(lensPosition, 0.0f);
Vector3 pointOffset = new Vector3(level.Player.Position.X, 
    level.Player.Position.Y - 32.0f, 0.0f);
Vector3 direction = rayStart - pointOffset;
Ray bulletRay = new Ray(rayStart, direction);

This ray always points straight down, which is not what you want.

Since you didn't tell us how your ray should be defined, I can't tell you exactly what code will fix your issue.

However, you should fix the above code so that pointOffset is a position that satisfies the following:

  • It is on the ray.
  • It is not the same as the player position.
  • It is between the player and the desired box to collide the ray with.

Diagram describing the function of the two Vector3 points.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .