Calculating Entity velocity

This seems like it should be pretty simple but I am having a hard time figuring it out.

I want to calculate the velocity of my character. E.G. the difference between it’s position in the current frame and it’s position in the previous frame.

I am having trouble saving the character “previous position” so I can access it in the current frame

So far I have this

// update code called every frame
Velocity.prototype.update = function(dt) {

var player =‘player’);

var prevPos = ?????;
var plyrPos = player.getPosition();

var x = prevPos.x - plyrPos.x;
var y = prevPos.y - plyrPos.y;
var z = prevPos.z - plyrPos.z;
var velicity = (x,y,z);


Any help would be appreciated!


You where super close, just had to set prevPos after calculating velocity. Its best to store it for re-use like so.


// initialize code called once per entity
Velocity.prototype.initialize = function() {
    // player: entity
    this.player ='player');
    // positional data
    this.previousPosition = new pc.Vec3();
    this.velocity = new pc.Vec3();



// update code called every frame
Velocity.prototype.update = function(dt) {
    // calculate velocity
    const position = this.player.getPosition();
    this.velocity.sub2(position, this.previousPosition);
    // store position as previous


Thanks so much pixelpros!

This works perfectly, and is a big help in understanding how better to set up scripts like this. I am very new to js in general so I appreciate the support.

1 Like