I created a weapon sway/bobbing script, but it causes the weapon to disappear when I use it. Not sure what the problem is.
Here is my project: PlayCanvas | HTML5 Game Engine
Here is the code for the specific script:
WeaponSway.prototype.initialize = function() {
this.intensity = 0.005; // adjust this to increase/decrease sway intensity
this.speed = 500; // adjust this to increase/decrease sway speed
this.defaultPosition = this.entity.getLocalPosition().clone();
this.sideIntensity = 0.003; // adjust this to increase/decrease side-to-side sway intensity
};
WeaponSway.prototype.update = function(dt) {
var camera = this.entity.parent;
var currentPosition = camera.getLocalPosition();
if (!currentPosition) {
return;
}
var xDiff = (this.defaultPosition.x - currentPosition.x) * this.intensity;
var yDiff = (this.defaultPosition.y - currentPosition.y) * this.intensity;
var zDiff = (this.defaultPosition.z - currentPosition.z) * this.sideIntensity;
this.entity.setLocalPosition(this.defaultPosition.x - xDiff, this.defaultPosition.y - yDiff, this.defaultPosition.z + zDiff);
this.defaultPosition.lerp(currentPosition, this.speed * dt);
console.log("Weapon position: ", this.entity.getLocalPosition());
};
lerp requires two vec3s to be passed into it and the lerp value. It’s currently disappearing because it’s calculating NaNs due to wrong objects and not enough parameters being passed to it.
OK, so I tried adjusting this.speed, which seems to have brought it back, but now everytime I launch the model slowly travels to the location of the camera (I believe the speed at which it does so is relative to this.speed).
Alright, I tried using Math.sin() instead, but now the weapon is in an odd position and not swaying.
Edit: I managed to fix the “odd position” of the weapon, but the weapon still does not move.
Edit 2: Script is now fixed