问题
My game scene consist of four walls, which are static bodies, and one platform plate, which is of type kinematic and slides only horizontally, something like the picture below.
The platform body moves based on acceleration sensor, see this codes
@Override
public void onAccelerationChanged(AccelerationData pAccelerationData) {
mPlatformBody.setLinearVelocity(pAccelerationData.getX() * 10, 0);
}
My problem is when the platform goes off the boundary walls, which it should not. For resolving this issue, I've set its velocity to zero once it tries to break out the boundaries. see this codes
Rectangle rect = new Rectangle(camWidth / 2 - 40, camHeight / 2 - 5,
80, 10, mEngine.getVertexBufferObjectManager()) {
@Override
protected void onManagedUpdate(float pSecondsElapsed) {
if (this.getX() <= 1) {
mPlatformBody.setLinearVelocity(0, 0);
}
if ((this.getX() + 80 >= camWidth - 1)) {
mPlatformBody.setLinearVelocity(0, 0);
}
super.onManagedUpdate(pSecondsElapsed);
}
};
With the codes above, still this platform can goes off the screen.
Could anyone please help me out how can I overcome this issue?
回答1:
As @LearnCocos2D stated, I should reset platform body to a legal position while it tries to leave the screen. For this, I should use setTransform
method of Body
class (as @iforce2d said).
For dealing with setTransform
, there is two important points.
- AndEngine uses top-left as anchor of sprites, but Box2d uses center as anchor of bodies.
- Box2d uses meter as its units, so we must tranform all pixel units to meter unit.
Example: Suppose we want to move body body to (3, 4) point (in pixels).
float x = 3; // in pixels (AndEngine unit)
float y = 4; // in pixels (AndEngine unit)
float wD2 = sprite.getWidth() / 2;
float hD2 = sprite.getHeight() / 2;
float angle = body.getAngle(); // preserve original angle
body.setTransform((x + wD2) / PIXEL_TO_METER_RATIO_DEFAULT,
(y + hD2) / PIXEL_TO_METER_RATIO_DEFAULT,
angle);
Note that PIXEL_TO_METER_RATIO_DEFAULT
is 32.
来源:https://stackoverflow.com/questions/28370020/how-to-not-allow-kinematic-physics-bodies-to-pass-through-static-bodies