问题
I have box2d body in Andengine.I wanna move this body from (0,0) to (100,100) at a time(constant speed).How can it be possible? I tried this code: this.body.setLinearVelocity(new Vector2(1, 0)); but it is moving non-stop.
回答1:
I guess the easiest way to move along a predefined path would be to use Body.setTransform(...)
. This way we basically ignore all forces, friction, torque, collisions etc and set the position of the body directly.
I don't know Andengine, so this is just pseudocode:
public void updateGameLoop(float deltaTime) {
Vector2 current = body.getPosition();
Vector2 target = new Vector2(100, 100);
if (!current.equals(target)) {
float speed = 20f;
Vector2 direction = target.sub(current);
float distanceToTarget = direction.len();
float travelDistance = speed * deltaTime;
// the target is very close, so we set the position to the target directly
if (distanceToTarget <= travelDistance) {
body.setTransform(target, body.getAngle());
} else {
direction.nor();
// move a bit in the target direction
body.setTransform(current.add(direction.mul(travelDistance)), body.getAngle());
}
}
}
来源:https://stackoverflow.com/questions/19471504/constant-box2d-body-moving-to-point-at-a-time