2013-01-21 128 views
0

我只是有一個簡短的問題! 我做了一個應用程序,隨機精靈在屏幕上繪製,我希望這些精靈不與其他人重疊(這些精靈是相同的圖片,但位置是隨機的)精靈和碰撞檢測cocos2d android

感謝您的幫助。

回答

0

要檢查精靈相交另一個可以使用

CCSprite *sprite1, *sprite2; 
if (CGRectIntersectRect(sprite1.boundingBox, sprite2.boundingBox)) { 
    // sprites are overlapping 
} 

這並沒有考慮到作爲旋轉計算將變得更加複雜。

如果要部署不重疊精靈的量我不明白,在這種情況下,一個公平的瑣碎方法如下:

CCNode *parent; 
for (int i = 0; i < AMOUNT; ++i) { 
    CCSprite *sprite = [CCSprite spriteWith..]; 
    bool isOk = false; 
    while (!isOk) { 
    sprite.position = ccp(...); 
    isOk = true; 
    for (CCSprite *sprite2 in parent) { 
     if (CGRectIntersectRect(sprite.boundingBox, sprite2.boundingBox)) { 
     isOk = false; 
     break; 
     } 
    } 
    } 
+0

我只有1個精靈,當我觸摸屏幕時,這個精靈會再次出現,但是具有不同的位置(例如,屏幕上會顯示2個「微笑的太陽」),所以我只想比較1個精靈只有1個精靈創造出來,但又一次又一次地用不同的姿勢加入。 – user1997570

+0

然後它比這更簡單,因爲你不需要外部循環。 – Jack

0

您可以使用ArrayList來保存先前的精靈(太陽)位置,並可以申請檢查時要添加新的太陽

ArrayList<CGRect> sunArrayList=new ArrayList<CGRect>(); 

立即申請退房,當你產生屏幕上的新精靈(太陽)

boolean exist;// variable to check position already exist 
do{ 
    exist=false; //set at every loop starting new no generated not exist we have to check this below. if exist change it to true 
    //generate no 
    int xRandom=3;//apply your logic for random location x 
    int yRandom=5;//apply your logic for random location y 

for(int i=0;i<sunArrayList.size();i++) 
{ 
    if(sunArrayList.get(i).contains(xRandom,yRandom)) 
    { 
     exist=true; 
    } 
} 

    if(exist==false)// means your generated location not exist 
    { 
     // add sun to screen with position xRandom,yRandom 
     //write code here to add sprite on screen (xRandom,yRandom) 

     /// 
     CGSize sunSize=CGSize.make(width, height); 
     //CGSizeSunSize=sprite(sun) slicing size 

CGPoint sunPos=new CGPoint(); 
     sunPos.set(xRandom, yRandom); 
CGRect randomLocationGeneratedSun=new CGRect(sunPos,sunSize); 
sunArrayList.add(randomLocationGeneratedSun); 
    } 

}while(exist)