Check for entity movement

I found this code somewhere on a forum and it sounded like it would be what I’m looking for, but it seems to be called way to frequently and always before my entities begin to move.

CheckRoll.prototype.update = function(dt)
        this.dice[i].currPos = this.entity.getLocalPosition();
        if(this.manager.script.gameManager.removedCoins === true)
            if(this.dice[i].currPos === this.dice[i].lastPos)
                console.log('Dice' + i + 'stopped');
            this.dice[i].lastPos = this.dice[i].currPos;

I’m not sure if I should make a new function for this, or add a timer/delay to the update.

Instead of a timer or a delay I would skip whole code until you applied the movement to your dices. A ‘started’ flag true/false could suffice.

This line doesn’t do a value copy, it just copies the reference so both variables now point to the same Vec3 object.

Assuming that this.dice[i].lastPos is already a Vec3, then you would want:


This line also doesn’t check by value, it just compares references:

this.dice[i].currPos === this.dice[i].lastPos

Comparing floating points for equal value generally doesn’t work due to floating point inaccuracy so you should check if the distance between the two points is lower than x. eg:

var d = new pc.Vec3();
d.sub2(this.dice[i].currPos, this.dice[i].lastPos);
if (d.lengthSq() < 0.01) {
  // Do something

Of course, since you are using physics, if you really want to know if something has stopped moving, you can check the rigid body’s velocity and if it’s below a certain value or 0, it has stopped moving.

1 Like

Ok, I understand how this would work. But would I have to write a new function to get the linear velocity or is there already one?

Right, that’s how to use it, but is there an inherent getVelocity() method in the engine, or do I

It is a property so you just access it directly.


if (this.entity.rigidbody.linearVelocity.lengthSq() > 0.01) {
  // Do something