2012-10-20 51 views
2

我正在開發一款使用jbox2d和jBox2d for android一起使用的遊戲。我想要檢測用戶是否觸摸了我世界中各個身體之間的特定動態身體。我已經嘗試遍歷所有的身體,並找到我的興趣之一,但它沒有爲我工作。請幫助 繼承人我所做的:如何檢測jBox2D中是否碰到特定的物體

@Override 
public boolean ccTouchesEnded(MotionEvent event) 
{ 
    CGPoint location = CCDirector.sharedDirector().convertToGL(CGPoint.ccp(event.getX(), 
      event.getY())); 

    for(Body b = _world.getBodyList();b.getType()==BodyType.DYNAMIC; b.getNext()) 
    { 
     CCSprite sprite = (CCSprite)b.getUserData(); 
     if(sprite!=null && sprite instanceof CCSprite) 
     { 
      CGRect body_rect = sprite.getBoundingBox(); 
      if(body_rect.contains(location.x, location.y)) 
      { 
       Log.i("body touched","<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); 
       expandAndStopBody(b); 
       break; 
      } 

     } 
    } 
return true; 
} 

觸摸後,系統繼續顯示GC_CONCURRENT釋放1649K,11130K自由/ 12935K 14%,暫停1毫秒+ 2ms的,一切都將掛樣態。

回答

0

您應該檢查以確保列表中的正文不爲空,例如

for (Body b = world.getBodyList(); b!=null; b = b.getNext()) 
{ 
    // do something 
} 

不知道這是否會解決掛起,但應該這樣做。

+0

寫入b = b.getNext()而不是簡單b.getnext()解決了「掛起」問題,但現在行爲很奇怪。除了被觸摸的身體之外,其他一些隨機的身體也表現得好像被觸摸一樣。不知道發生了什麼,但可能是我將多個身體添加到世界的方式導致了probs。我已經調用了代碼來在循環中添加一個body。這樣做是錯誤的嗎?另外,請在b = b.getNext()魔術上點亮一些。謝謝 – rahil008

+0

魔術實際上是b!= null,因爲它在到達列表末尾(鏈表列表約定)時退出循環。當到達結尾時,b將等於null。關於您的其他問題,我會建議在Cocos2d論壇或jBox2d論壇上發佈問題。這是一個非常專業化的問題,我認爲來自這些論壇的觀衆會更有能力提供幫助。 – SolidRegardless

1

要檢查身體是否被觸摸,您可以使用世界對象的方法queryAABB。我嘗試重新排列您的代碼以使用該方法:

// to avoid creation every time you touch the screen 
private QueryCallback qc=new QueryCallback() { 

    @Override 
    public boolean reportFixture(Fixture fixture) { 
      if (fixture.getBody()!=null) 
      { 
        Body b=fixture.getBody(); 
        CCSprite sprite = (CCSprite)b.getUserData(); 
        Log.i("body touched","<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");   
        expandAndStopBody(b); 
      } 
      return false; 
    } 
}; 

private AABB aabb; 

@Override 
public boolean ccTouchesEnded(MotionEvent event) 
{ 
    CGPoint location = CCDirector.sharedDirector().convertToGL(CGPoint.ccp(event.getX(), event.getY())); 

    // define a bounding box with width and height of 0.4f 
    aabb=new AABB(new Vec2(location.x-0.2f, location.y-0.2f),new Vec2(location.x+0.2f, location.y+0.2f));    
    _world.queryAABB(qc, aabb);    

    return true; 
} 

我嘗試減少垃圾回收器,但有些東西必須立即執行。 有關http://www.iforce2d.net/b2dtut/world-querying的更多信息

相關問題