-1

I have an origin of a line at point (xo, yo), and I have multiple "walls" which are square rectangles with x and y values at the top left corner. The line is meant to follow something (the player as a motion tracker to be specific), but it should not go past a wall.

So as soon as the line hits any part of the wall, it will not go past it. I know how to tell if the line collides with the wall using rectangle2d.intersects but I need to know exactly where it does that so the endpoint of the line would be that point.

Miles
  • 487
  • 3
  • 12

2 Answers2

0

You will need to make a new line for each side of the rectangle, then check collisions with each side. To make a simple method, you could have an array that contains each intersection with the rectangle. Top: point[0] Bottom: point[1] Left: point[2] Right: point[3] In your case you would need to take into account the direction the line was going so that you would know which side to go with; basically, if xo < rectangle.getX() you go with the bottom side else you go with the top side, if yo < rectangle.getY() you go with the left side else you go with the right side.

public Point2D[] getIntersectionPoint(Line2D line, Rectangle2D rectangle) {

       Point2D[] point = new Point2D[4];

        point[0] = getIntersectionPoint(line,new Line2D.Double(rectangle.getX(),rectangle.getY(),rectangle.getX() + rectangle.getWidth(),rectangle.getY()));
        point[1] = getIntersectionPoint(line,new Line2D.Double(rectangle.getX(),rectangle.getY() + rectangle.getHeight(),rectangle.getX() + rectangle.getWidth(),rectangle.getY() + rectangle.getHeight()));
        point[2] = getIntersectionPoint(line,new Line2D.Double(rectangle.getX(),rectangle.getY(),rectangle.getX(),rectangle.getY() + rectangle.getHeight()));
        point[3] = getIntersectionPoint(line,new Line2D.Double(rectangle.getX() + rectangle.getWidth(),rectangle.getY(),rectangle.getX() + rectangle.getWidth(),rectangle.getY() + rectangle.getHeight()));

        return p;

    }
Caleb Limb
  • 304
  • 1
  • 11
  • You should only need to take into account the width and height of the rectangle if the origin of your line is inside of the rectangle. – Caleb Limb May 13 '15 at 00:56