pc.script.create('pc:third_person_camera', function (context) {
var attr = {
DISTANCE: 1.5,
ENTITY_NAME: 'camera target',
X_SCALE: 0.1,
Y_SCALE: 0.1,
X_LIMIT: 0.15,
Y_LIMIT: 0.15,
MIN_PITCH: -0.1,
MAX_PITCH: 0.1
};
var ThirdPersonCamera = function (entity) {
this.entity = entity;
// euler angles
this.x = attr.MIN_PITCH;
this.y = Math.PI;
this.lasth = 0;
this.lastv = 0;
};
ThirdPersonCamera.prototype = {
initialize: function () {
this.targetEntity = context.root.findByName(attr.ENTITY_NAME);
},
update: function (dt) {
if (!context.controller) {
return;
}
var lookx = context.controller.getAxis('lookx');
var looky = context.controller.getAxis('looky');
var x = lookx * lookx;
var y = looky * looky;
var xSign = lookx > 0 ? 1 : -1;
var ySign = looky > 0 ? 1 : -1;
x = xSign * x * attr.X_SCALE;
y = ySign * y * attr.Y_SCALE;
var dh = pc.math.clamp(x, -attr.X_LIMIT, attr.X_LIMIT);
var dv = pc.math.clamp(y, -attr.Y_LIMIT, attr.Y_LIMIT);
dh = this.lerp(this.lasth, dh, 0.5);
dv = this.lerp(this.lastv, dv, 0.5);
this.x += dv;
this.x = pc.math.clamp(this.x, attr.MIN_PITCH, attr.MAX_PITCH);
this.y -= dh;
if (this.y < 0) {
this.y += Math.PI * 2;
} else if (this.y > Math.PI * 2) {
this.y -= Math.PI * 2;
}
this.lasth = dh;
this.lastv = dv;
this.entity.setPosition(this.targetEntity.getPosition());
this.entity.setEulerAngles(this.x * pc.math.RAD_TO_DEG, this.y * pc.math.RAD_TO_DEG, 0);
this.entity.translateLocal(0, 0, attr.DISTANCE);
},
lerp: function (value, target, t) {
return value + (target - value) * t;
},
};
return ThirdPersonCamera;
});
Why are you posting this? I would recommend against using the old script format that you have here. Instead, I strongly advise you use the current script format outlined here:
https://developer.playcanvas.com/en/user-manual/scripting/anatomy/