簡體   English   中英

如何檢測jBox2D中是否觸摸了特定的身體

[英]How to detect if a particular body is touched in jBox2D

我正在與jBox2d結合使用jbox2d和android開發游戲。 我想檢測用戶是否在我的世界中的各個物體中觸摸了特定的動態物體。 我嘗試遍歷所有身體,發現我的興趣之一,但對我沒有用。 請幫我這里做的事情:

@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,釋放了14%的11130K / 12935K,暫停了1ms + 2ms,一切都變得像掛起狀態。

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

// 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的更多信息

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

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

不知道這是否可以解決掛起問題,但應該這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM