Search code examples
rotationlibgdxbox2dsmoothing

Libgdx Box2D smooth angular rotation


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());
        }

Solution

  • 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.