如何找出线与某物碰撞的位置?

时间:2015-05-13 00:24:19

标签: java line collision java-2d

我在点(xo,yo)有一条线的起源,我有多个"墙"这是方形矩形,左上角有x和y值。这条线是为了追随某些东西(玩家作为一个特定的运动追踪器),但它不应该经过一堵墙。

一旦线撞到墙壁的任何部分,它就不会越过它。 我知道如何判断线是否使用rectangle2d.intersects与墙碰撞,但我需要知道它的确切位置,因此线的端点就是那个点。

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

您需要为矩形的每一边创建一条新线,然后检查每一侧的碰撞。要创建一个简单的方法,您可以拥有一个包含矩形的每个交集的数组。顶部:point[0]底部:point[1]左:point[2]右:point[3]在您的情况下,您需要考虑线路的方向,以便您知道哪个一边走;基本上,如果xo < rectangle.getX()使用底边else,则使用顶边,如果yo < rectangle.getY()使用左侧else则使用右边。

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;

    }