2014-01-09 99 views
0

我正在使用iOS/xcode中的cocos2d和box2d應用程序。僅在cocos2d/box2d中碰撞一側

我有一個移動的精靈和一些方形框,我可以檢測到碰撞沒有問題,並且工作正常。

但是,我需要檢查目標一側的碰撞,並根據精靈命中目標的哪一側有不同的行爲。

想象它像一個有3個封閉邊和一個開放的盒子 - 如果精靈碰到三個閉合邊中的任何一個,那麼它應該失敗/死亡,但是如果它與目標的「打開」邊相碰撞,那麼它應該落入。

因此,我需要能夠分辨出碰撞的一側而不是另一側的碰撞,而不僅僅是檢查是否有碰撞。

任何想法/建議?

+0

可以附加通過持合資另一薄盒(如線)你箱的一側,並給它一個用戶數據,然後檢查碰撞 – Singhak

+0

什麼辛哈克說,除了你不需要焊接接頭和獨立的機身,你可以把更多的固定裝置放在原來的身體上。 – iforce2d

+0

我一直在考慮辛哈克的建議 - 創建兩個獨立的機構,一個包含較小一個的三個邊。你能否擴展你的建議:「你可以把更多的燈具放在原來的身體上」? – Richard

回答

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. S.這種解決方案是偉大的,如果箱子沒有旋轉。如果旋轉的 - 你需要使用的東西計算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);