问题
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());
}
回答1:
I'm assuming this code is in your update loop.
Create an instance variable angleTarget.
Every update loop:
Set angleTarget to your mouse angle.
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.
回答2:
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.
来源:https://stackoverflow.com/questions/25039186/libgdx-box2d-smooth-angular-rotation