[SOLVED] Camera Not Rotating

I’m trying to make it so that the camera rotates 180 degrees in the Y when the player is behind the camera, and set the camera back to 0 degrees in the Y when the player is in front of the camera. Problem is, it doesn’t rotate. I think what happens is that the camera rotates 180 degrees for a few seconds and then is set back for some reason. I’m not whether it’s my code, or if I need to change some variables. Can someone help me with what I’m trying to accomplish?

var CameraScript = pc.createScript('cameraScript');

//Attributes
CameraScript.attributes.add("player", { type: 'entity', title: 'Player' });

//Variables
var canMove = true;

// 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) {
     if (canMove === true) { 
        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.getPosition().y, this.pivotPoint);
        this.entity.translateLocal(this.offset, this.entity.getPosition().y, this.offset);
     }
    
    
    if (this.app.keyboard.wasPressed(pc.KEY_S)) {
        canMove = false;
    }
    else if (this.app.keyboard.wasReleased(pc.KEY_S)) {
        canMove = true;
    }
    
    if (this.player.getPosition().z > this.entity.getPosition().z) {
        this.entity.setEulerAngles(this.entity.getEulerAngles().x, 180, this.entity.getEulerAngles().z);
    }
    if (this.player.getPosition().z < this.entity.getPosition().z) {
        this.entity.setEulerAngles(this.entity.getEulerAngles().x, 0, this.entity.getEulerAngles().z);
    }
};

Link To Editor: https://playcanvas.com/editor/scene/917896

It’s probably due to the the different ways that a single rotation of an object. In the engine, rotation is not stored as euler angles.

Depending on how the camera works, either store the X, Y and Z euler angles in the script and use them rather than getting it from the entity or use the rotate/rotateLocal function instead.

1 Like

I made variables for the x, y, and z. Then I changed the variables value, rather then doing it directly in a new instance every time.