Enable path following when struck

Hello, usually an npc go straight to player when player is far enough, i want that when the npc is truck against a wall for example, a path following get enabled so i thought of a line like this one

else if ((this.state === "walking" || this.state==='run' ) && speed<0.06) {
enable path code
}

but it’s incomplete since when the npc start to follow the player his speed is still under 0.06 so the path get enabled, i need something that when speed is lower than 0.06 for more than x seconds the path get enabled, how do i do that?

You will need to trigger your pathfinding code after x seconds have passed. To do that you need a counter that keeps track of the time that has elapsed as soon as the speed gets lower to 0.06.

You can use the update(dt) method all Playcanvas scripts provide for that:

// initialize code called once per entity
MyScript.prototype.initialize = function() {
    this.duration = 0;
};

// update code called every frame
MyScript.prototype.update = function(dt) {
    
    if ((this.state === "walking" || this.state==='run' ) && speed<0.06 && this.duration === 0) {

        // start counting time
        this.duration += dt;

        // execute pathfinding code after 6 seconds have elapsed, and stop counting time
        if ( this.duration > 6 ){
           this.duration = 0;
           this.myPathfindingMethod();
        }
    }
};

Thanks Leonidas i was just checking about that too :stuck_out_tongue: seems sometime writing down questions helps to think more clearly. Anyway thanks a lot for your support. Always precious.

1 Like

You are welcome, fixed a typo, counter should start from 0 to be able to add the dt on each frame.

1 Like