2014-12-26 33 views
1

目的是限制一個box2d的物理體的移動在一定的軸 - 向水平或垂直移動,這裏是主體定義:限制沿軸線在andEngine Box2D的身體的運動

Body ballBody; 
Sprite ball;  
ball = new AnimatedSprite(x_end, y_end-ballTextureRegion.getHeight(), this.ballTextureRegion, this.getVertexBufferObjectManager()); 
ballBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, ball, BodyType.DynamicBody, FIXTURE_DEF); 
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(ball, ballBody, true, true)); 
scene.registerUpdateHandler(this.mPhysicsWorld); 
scene.attachChild(ball); 

的在所有方向上球移動,通過使用andEngines IAccelerationListener,什麼已經嘗試限制沿x軸的主體,加速度計,以便它使只有垂直:

在主遊戲循環,已經設置其線速度爲0的x分量:

scene.registerUpdateHandler(new IUpdateHandler() { 

    public void reset() { 
    } 

    // main game loop 
    public void onUpdate(float pSecondsElapsed) { 
     ballBody.setLinearVelocity(0, ballBody.getLinearVelocity().y); // set x velocity as 0 
    } 
}); 

但現在球也可以水平移動,其水平速度現在較小但不是全爲0.如何限制其沿一個方向的移動?

回答

1

我從動態變化的Box2D的物體的種類,以運動解決了這個問題,從here瞭解身體類型,發現在我的情況下,運動的身體是一個動態的身體天色漸受一切力量更好物理世界。

ballBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, ball, BodyType.KinematicBody, FIXTURE_DEF); 

,並設置其沿y軸的速度這樣的垂直運動:

penBody.setLinearVelocity(mPhysicsWorld.getGravity().x, 0);