Libgdx Box2D smooth angular rotation

2019-06-13 15:26发布

I'm currently developing a flying game in libgdx where you can control the rotation of a bird with the mouse cursor. Right now the bird will instantly rotate to the cursor position. I'm aiming to make the bird rotation lag behind a little bit to make the flying seem more smooth. Rotational damping wont work because i am using the setTransform() method. I would be very happy about any suggestions, this is the code controlling the rotation, it's called every frame in the render method:

    //get cursor pos
    cursorPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
    camera.unproject(cursorPos);
    //get bird pos
    birdPos.set(body.getPosition().x, body.getPosition().y, 0);
    //birdpos-cursorpos
    birdPos.sub(cursorPos);
    //new vector which is pointing from bird to cursor
    direction.set(birdPos.x, birdPos.y);
    //get current linear velocity
    movement.set(body.getLinearVelocity());
    //apply rotation to bird if cursor is not too close
    if (Math.sqrt(Math.pow(direction.x, 2) + Math.pow(direction.y, 2)) > 1) {
        body.setTransform(body.getPosition().x, body.getPosition().y,   direction.angleRad());
        }

2条回答
啃猪蹄的小仙女
2楼-- · 2019-06-13 16:31

Instead of keeping track of your bird's xSpeed and ySpeed, give it a heading (in degrees) and a speed. Convert that heading and speed to an xSpeed and ySpeed using basic trig whenever you need to move your bird.

Then to give your bird a smoother path, figure out the "goal heading" (again, in degrees) from the bird to the goal. Change your bird's heading over time until it matches the goal heading.

查看更多
你好瞎i
3楼-- · 2019-06-13 16:33

I'm assuming this code is in your update loop.

Create an instance variable angleTarget.

Every update loop:

  1. Set angleTarget to your mouse angle.

  2. Use setPosition to set the actual body angle to: body.angle = body.angle + (angleTarget - body.angle) * 0.05

Usually that expression is put in a function called lerp, which stands for linear interpolation. Look up 'lerp function' to read more about this.

查看更多
登录 后发表回答