Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;
share|improve this question
Should the ray be pointing straight down? (It's vertical.) – Olhovsky Jun 1 '11 at 20:33
The Ray should be should be pointing anywhere from down and right to down and left depending on where the character is – dbomb101 Jun 1 '11 at 20:53
"I'm checking to see if I've created is intersecting with a rectangle." ...What? – AttackingHobo Jun 1 '11 at 22:09
Fixed that typo for you AttackingHobo -- he meant "...if the ray I've created is...". – Olhovsky Jun 1 '11 at 22:10
up vote 4 down vote accepted

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.