How to apply lerpAngle to an entity?

Hi, I need to use the lerpAngle function on an entity. Right now, the code I have is this:

var zrot = pc.math.clamp(this.velocity, -2, -0.75);
zrot += 1;
this.entity.setLocalEulerAngles(0, 0, zrot * 90);

This works on the ‘bird’ entity (I’m making a Flappy Bird game), but once he jumps, and starts facing down towards the floor, and you press again, the entity leaps back up.

How do you get this to be smooth with lerpAngle?

You can do this in two ways:

  1. Using the PlayCanvas tween library (easiest way), check the rotation example: https://developer.playcanvas.com/en/tutorials/tweening/

  2. Using lerpAngle as you said, some pseudo code that demonstrates lerping between a start and an end angle:

MyScript.prototype.update = function(dt) {
    if( animationStarted === true){ 
        this.alpha += this.rotationSpeed * dt;
        var angle = pc.math.lerp(this.startAngle, this.endAngle, this.alpha);
        this.entity.setLocalEulerAngles(0, 0, angle);
    }
};

The code returns

Cannot find variable animatedStarted

How to fix this?

Hi @_Lio3LivioN, the code I posted is just an example to demonstrate the logic. You should rename the variables to the ones you use in your code.

If you still have issues, try posting a sample project here with your existing code to take a look at.

How would you do this with the tween library? This seems a lot more simple to me (I’m learning how to code)

here is my project: https://playcanvas.com/project/572229/overview/flappy-bird-30fps
(goto bird.js)
thank you for any help :slight_smile:

This project uses an older version of the tween.js library, not the one encapsulated to be used with pc.Entities. If you are learning right now I wouldn’t recommend doing this using that older library.

As you posted above, the original project uses something similar to lerping (adding 1 degree per frame and clamping between two values) to animate the sprite. This makes the bird smoothly look down while falling.

The snapping happens because when you click the velocity is increased rapidly, making the animation follow that in an instant:

    // bird.js, line 73 on the original Flappy Bird codebase
    if (this.state === 'play') {
        app.fire('game:audio', 'Flap');
        this.velocity = this.flapVelocity;
    }

Thinking there are two ways to do what you want:

  • change the way the flapping works, instead of adding the velocity on click at the same frame, do this in a duration e.g. 0.5 seconds (this seems easier given the existing code)
  • decouple the animation code (setLocalEulerAngles) from the velocity and use tweening in a fixed duration to rotate up/down the bird.