简体   繁体   English

2D运动物体碰撞

[英]2D moving object collision

I 'm creating a two 2D simulation and I need to determine if 2 moving objects A and B will cross paths . 我正在创建两个2D模拟,我需要确定2个移动对象AB是否会穿过路径。 A moves with a constant speed Va and B with Vb . AVb等速移动Va和B。

I'm able to determine the point where the the object's path intersect but I can't figure out if will they actually collide. 我能够确定对象的路径相交的点,但是我无法弄清楚它们是否会发生碰撞。

I calculated the point of collision using 我使用计算了碰撞点

This formula 这个公式

and the same for y y

Let's consider case of two axis-aligned rectangles. 让我们考虑两个轴对齐的矩形的情况。 They do intersect, if projections of both to X-axis intersect, and projections of both to Y-axis intersect. 如果两者在X轴上的投影相交,并且两者在Y轴上的投影相交,则它们确实相交。 在此处输入图片说明

First rectangle coordinates (Ax1,Ay1),(Ax2,Ay2), velocity vector (VAx,VAy) 第一个矩形坐标(Ax1,Ay1),(Ax2,Ay2),速度矢量(VAx,VAy)
Second rectangle coordinates (Bx1,By1),(Bx2,By2), velocity vector (VBx,VBy) 第二个矩形坐标(Bx1,By1),(Bx2,By2),速度矢量(VBx,VBy)

Time interval when X-projections intersect: X投影相交的时间间隔:

Ax2+VAx*t1=Bx1+VBx*t1
t1=(Bx1-Ax2)/(VAx-VBx)
t2=(Bx2-Ax1)/(VAx-VBx)

Interval is Ix=(t1,t2) (or (t2,t1) if t2 < t1) 间隔为Ix=(t1,t2) (或者如果t2 <t1,则为(t2,t1))

For Y-projections 对于Y投影

u1=(By1-Ay2)/(VAy-VBy)
u2=(By2-Ay1)/(VAy-VBy)

Interval is Iy=(u1,u2) (or (u2,u1) if u2 < u1) 间隔为Iy=(u1,u2) (如果u2 <u1则为(u2,u1)

Check if these two time ranges Ix and Iy intersect. 检查这两个时间范围Ix和Iy是否相交。 If they do, objects collide. 如果存在,则物体会碰撞。

This is how I have it setup in my code, although it probably won't work to simply add this to your code, hopefully this will help you make sense of the math: 这就是我在代码中设置的方式,尽管将其简单地添加到代码中可能无法正常工作,但希望这将有助于您理解数学:

rectangleIntersect() will return true if the two objects have intersected. 如果两个对象相交,则rectangularIntersect()将返回true。

public static boolean intersectRange(int min, int max, int min2, int max2){
    return Math.max(min, max) >= Math.min(min2, max2) && 
           Math.min(min, max) <= Math.max(min2, max2);
}

public static boolean intersectRange(float min, float max, float min2, float max2){
    return Math.max(min, max) >= Math.min(min2, max2) && 
           Math.min(min, max) <= Math.max(min2, max2);
}

public static boolean rectangleIntersect(Rectangle rect, Rectangle rect2){
    return intersectRange(rect.getX(), rect.getX() + rect.getWidth(), rect2.getX(), rect2.getX() + rect2.getWidth()) &&
            intersectRange(rect.getY(), rect.getY() + rect.getHeight(), rect2.getY(), rect2.getY() + rect2.getHeight());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM