[SOLVED] Check if the distance becomes larger

What is an easy way to check if the distance becomes larger between an enemy and the player?
I like to would build in a small buffer to.

Something like:

if (this.previousDistance + 1 < this.currentDistance) {
playerMovesAway = true;
}

Something like this might help you, it uses the new distance method available in the pc.Vec3 class:

var Distance = pc.createScript('distance');

// initialize code called once per entity
Distance.prototype.initialize = function() {
  
    this.vec = new pc.Vec3();
    
    this.previousDistance = 0;
};

// update code called every frame
Distance.prototype.update = function(dt) {
  
    this.vec.copy(enemy.getPosition());
    var distance = this.vec.distance(player.getPosition());
    
    if (distance - this.previousDistance > 0) {
        playerMovesAway = true;
    }
    
    this.previousDistance = distance;
    
};
1 Like

With this:

this.vec.copy(this.entity.getPosition());
var distance = this.vec.distance(player.getPosition());

if (distance - this.previousDistance  > 0) {
    this.playerMovesAway = true;
    console.log(this.playerMovesAway);
}

else {
    this.playerMovesAway = false;
    console.log(this.playerMovesAway);
}

this.previousDistance = distance;

it’s flipping around between true and false so that’s why i think i need to implant a small buffer, but i don’t get it working…

Okay it looks like it works. It’s only flipping around between true and false at start.

1 Like