Constant box2d body moving to point at a time [closed]

对着背影说爱祢 提交于 2020-02-02 16:28:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!