Now I’ve been trying to get the camera movement working for my game. I first tried making the camera a child of the player, but since the player rotates while moving, it affects the camera as well. Next, I tried creating a Camera Script and setting the camera’s X and Y position equal to the player’s, but this caused the movement to look very laggy. I tried doing some complicated arrangements last, but it didn’t work quite well. How should I add camera movement in a situation like this?
Here is a way to smooth out your camera when following the ball:
var CameraScript = pc.createScript('cameraScript');
//Attributes
CameraScript.attributes.add("player", { type: 'entity', title: 'Player' });
// initialize code called once per entity
CameraScript.prototype.initialize = function() {
this.pivotPoint = new pc.Vec3();
// --- the smoothness of the camera, larger values make the movement smoother
this.inertia = 0.15;
// --- the initial offset of the camera position set in editor
this.offset = this.entity.getLocalPosition().clone();
};
// update code called every frame
CameraScript.prototype.update = function(dt) {
var inertiaFactor = Math.min(dt / this.inertia, 1);
var pos = this.player.getPosition();
// --- here is where we smooth out the current position based on the inertia factor
this.pivotPoint.lerp(this.pivotPoint, pos, inertiaFactor);
this.entity.setPosition(this.pivotPoint);
this.entity.translateLocal(this.offset);
};