Sound glitching

Hello, I need help to my script. The script works but the sound is glitching when the ‘Player’ is moving

Here is the project:
https://playcanvas.com/editor/scene/1757634

and here is the script:

var StoneFootstep = pc.createScript(‘stoneFootstep’);

// initialize code called once per entity
StoneFootstep.prototype.initialize = function() {
this.playerEntity = this.entity.root.findByName(‘Player’);
this.collisionEntity = this.entity.root.findByName(‘Collision Stone’);
this.playerEntity.hasEntered = false;

this.entity.collision.on('triggerenter', this.onCollisionEnter, this);
this.entity.collision.on('triggerleave', this.onCollisionLeave, this);

};

// update code called every frame
StoneFootstep.prototype.update = function(dt) {
if (this.playerEntity.hasEntered && this.playerEntity.rigidbody && this.playerEntity.rigidbody.linearVelocity.length() > 0) {
// Player is moving, play the sound
var speedMultiplier = this.playerEntity.rigidbody.linearVelocity.length() / 2.0; // Adjust the multiplier as needed
this.collisionEntity.sound.pitch = speedMultiplier;
this.collisionEntity.sound.play(‘Footstep’);
} else {
// Player is not moving, stop the sound
this.collisionEntity.sound.stop(‘Footstep’);
}
};

StoneFootstep.prototype.onCollisionEnter = function() {
this.playerEntity.hasEntered = true;
};

StoneFootstep.prototype.onCollisionLeave = function() {
this.playerEntity.hasEntered = false;
};

Basically i was trying to make a dynamic footsteps in onCollision function and yeah i dont know why my sound is acting up like this.

Hi @Drake_Aurin,

It may be the case that you are start playing the sound per frame in your update method.

You should rework your code to call play on the sound when the player enters the triggers (looped) and stop() it when he exits.

1 Like

Hey thanks for the reply!

That was the first version of script i made but the looping sound wont stop unless i leave the trigger. What I plan to do is when the Player stopped moving the sound will also stop but will play again when the Player moves.