且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为弹跳球创建碰撞检测?

更新时间:2022-04-26 21:59:22

对任意形状的碰撞检测通常非常棘手,因为您必须确定是否有任何像素碰撞。

Collision detection for arbitrary shapes is usually quite tricky since you have to figure out if any pixel collides.

使用圆圈实际上更容易。如果您有两个半径分别为r1和r2的圆,则如果中心之间的距离小于r1 + r2,则会发生碰撞。

This is actually easier with circles. If you have two circles of radius r1 and r2, a collision has occurred if the distance between the centers is less than r1+r2.

两个中心之间的距离(可以将x1,y1)和(x2,y2)进行计算并比较为:

The distance between the two centers (x1,y1) and (x2,y2) can be calculated and compared as:

d = sqrt((y2-y1) * (y2-y1) + (x2-x1) * (x2-x1));
if (d < r1 + r2) { ... bang ... }

或者,就像jfclavette指出的那样,平方根很昂贵,因此使用简单的操作进行计算可能会更好:

Or, as jfclavette points out, square roots are expensive so it may be better to calculate using just simple operations:

dsqrd = (y2-y1) * (y2-y1) + (x2-x1) * (x2-x1);
if (dsqrd < (r1+r2)*(r1+r2)) { ... bang ... }

计算新的运动向量(给定对象的(x,y)随时间变化的速率)是一个棘手的问题,因为您需要考虑当前的运动向量和

The tricky bit comes in calculating the new movement vectors (the rate at which (x,y) changes over time for a given object) since you need to take into account the current movement vectors and the point of contact.

我认为,首先,您应该反转运动矢量以测试碰撞检测是否首先起作用。

I think as a first cut, you should just reverse the movement vectors to test if the collision detection works first.

然后再问一个问题-***保持个别问题的具体性,以便可以针对性地回答。

Then ask another question - it's better to keep individual questions specific so answers can be targeted.