Lerping position of camera

Good morning, as i found out - math.lerp is my main enemy, i can never set it to work the way i want it. This is the line i want to lerp

cameraObject.getLocalPosition().z = playerPosition.z;

It sets camera Z position to Player Z position so camera is moving along my player, but i wanted it to make the smoother way and i tried this:

cameraObject.getLocalPosition().z = pc.math.lerp(cameraObject.getLocalPosition().z, playerPosition.z, 5*dt);

I also tried this:

var r = new pc.Vec3(0, 0, 0);

cameraObject.getLocalPosition().z = r.lerp(cameraObject.getLocalPosition().z, playerPosition.z, 5*dt);

but no success at all

Hello @smokys! Probably this forum topic can help you:


Yes the script would be looking like this:

var lerpedPosition = new pc.Vec3();
var cameraObject = this.app.root.findByName('Camera');
var playerPosition = this.app.root.findByName('Angle').getPosition();

lerpedPosition.lerp(cameraObject.getLocalPosition().z, playerPosition.z, 5 * dt);

if this should work, well it isnt :stuck_out_tongue:

because last line says setLocalPositions to all three vectors, and i need to define just Z somehow, but i have no clue how to do that

Correct me if iā€™m wrong, but I think something like this:

lerpedPosition.lerp(cameraObject.getLocalPosition(), playerPosition, 5 * dt);
cameraObject.setLocalPosition(cameraObject.getLocalPosition().x, cameraObject.getLocalPosition().y, lerpedPosition.z);
1 Like

A minor optimization: instead of querying local position 3 times, you can do it only once:

var pos = cameraObject.getLocalPosition();
lerpedPosition.lerp(pos, playerPosition, 5 * dt);
cameraObject.setLocalPosition(pos.x, pos.y, lerpedPosition.z);

Actually, thinking about it, you only need Z axis to be lerped, so:

var pos = cameraObject.getLocalPosition();
var zAxis = pos.z;
var z = pc.math.lerp(zAxis , playerPosition.z, 5 * dt);
cameraObject.setLocalPosition(pos.x, pos.y, z);

Here is the link, at the start when camera switch its angle there should be camera smoohly following player but instead i get this: https://launch.playcanvas.com/1031836?debug=true

move: up arrow key

It is actually working but my camera is sthill behind player and cant catch him somehow, seem to be too slow or what

var z = pc.math.lerp(zAxis , playerPosition.z, 5 * dt);
here 5 is simply the speed, for it to be faster just increase 5.

1 Like

I see. So, your camera changes views. Lerping only a single Z axis is not enough for the side view. You should find the optimal position of the camera, that is where it should end up at, and lerp to that target using all 3 axis.