[SOLVED] A way to calculate overall velocity without doubling?

I was looking for the best way to calculate velocity without it doubling when heading in a diagonal direction? For example when I go straight velocity is 20 but when I walk diagonally its 30

This is what I have so far:

var PlayFootsteps = pc.createScript('playFootsteps');

// initialize code called once per entity
PlayFootsteps.prototype.initialize = function () {
    this.entity.collision.on('collisionstart', this.onCollisionStart, this);
    this.entity.collision.on('collisionend', this.onCollisionEnd, this);
    var walking = false;
    var running = false;

};
var velocity = 0

// update code called every frame
PlayFootsteps.prototype.update = function(dt) {
    velocity = this.roundToTwo(this.entity.rigidbody.linearVelocity.x) + this.roundToTwo(this.entity.rigidbody.linearVelocity.z)
/*
    if (onground == true) {
        if (!this.entity.sound.slot('walk').isPlaying) {
            if(this.entity.sound != null) {
                this.entity.sound.play("walk");
    }
        }
    } else {
        //this.entity.sound.stop('walk')
    }
    */
};
PlayFootsteps.prototype.roundToTwo = function(num) {
    return +(Math.round(num + "e+2")  + "e-2");
}
// swap method called for script hot-reloading
// inherit your script state here
// PlayFootsteps.prototype.swap = function(old) { };

// to learn more about script anatomy, please read:
// https://developer.playcanvas.com/en/user-manual/scripting/

I probably wouldn’t play footstep sounds based on the entity’s velocity. It’s probably better to track how far the entity has moved. Here’s a sketch of a script (untested):

var FootstepSound = pc.createScript('footstepSound');

FootstepSound.prototype.initialize = function() {
    this.lastPosition = this.entity.getPosition().clone();
    this.distanceSinceLastStep = 0;
    this.stepDistance = 1; // Distance for one step, adjust as needed
};

FootstepSound.prototype.update = function(dt) {
    const currentPosition = this.entity.getPosition();
    this.distanceSinceLastStep += currentPosition.distance(this.lastPosition);

    if (this.distanceSinceLastStep >= this.stepDistance) {
        // Randomize the footstep pitch a bit for variation
        const pitch = pc.math.random(0.8, 1.2);
        this.entity.sound.pitch = pitch;
        this.entity.sound.play('footstep'); // Set up a sound component with this slot name
        this.distanceSinceLastStep = 0;
    }

    this.lastPosition.copy(currentPosition);
};

alr ill see if this works, if it doeset ill see if i can fix it

1 Like

this works great but do you have any recommended sounds? the one im using is a bit annoying

thanks bro