仅在cocos2d / box2d中的一侧发生碰撞

时间:2014-01-09 00:54:46

标签: ios cocos2d-iphone box2d collision-detection

我正在iOS / xcode中使用cocos2d和box2d处理应用程序。

我有一个移动的精灵和一些方框,我可以检测到碰撞没问题,而且工作正常。

我只需要检查目标一侧的碰撞,并根据精灵命中目标的哪一侧有不同的行为。

把它想象成一个有3个封闭边和一个打开的盒子 - 如果精灵击中三个封闭边中的任何一个然后它会失败/死亡,但如果它与目标的“开放”边缘碰撞,那么它应该落入。

所以我需要能够分辨出一方碰撞另一方碰撞之间的区别,而不仅仅是检查碰撞。

有任何想法/建议吗?

1 个答案:

答案 0 :(得分:0)

你知道框的边框。假设它只允许从盒子的左侧穿过。

CGPoint p1; // touch previous position
CGPoint p2; // touch current position
CGRect r = box.boundingBox;
CGPoint A = r.origin;
CGPoint B = ccpAdd(A, ccp(0.f, r.size.height));

// we have the straight line AB
// if p1 is on the left side of AB and
// p2 is on the right side of AB
// then path is allowed
//
// d1 is side indicator of p1
// d2 is side indicator of p2
// if di < 0, then pi is on the left side of AB
// if di == 0, then pi is on AB
// if di > 0, then pi is on the right side of AB
// if the line is horizontal, di < 0 if the point is above the line

float d1 = (p1.x - A.x) * (B.y - A.y) - (B.x - A.x) * (p1.y - A.y)
float d2 = (p2.x - A.x) * (B.y - A.y) - (B.x - A.x) * (p2.y - A.y)

BOOL isAllowed = d1 < 0 && d2 > 0; // you can use >= and <=

希望这会对你有所帮助。

P上。如果盒子没有旋转,这个解决方案很棒。如果旋转 - 您需要使用

之类的东西计算A和B点
/** Rotates a point counter clockwise by the angle around a pivot
 @param v is the point to rotate
 @param pivot is the pivot, naturally
 @param angle is the angle of rotation cw in radians
 @returns the rotated point
 @since v0.99.1
 */
CGPoint ccpRotateByAngle(CGPoint v, CGPoint pivot, float angle);