Tweening to an object that is moving actively

I want to create a chase mechanic. When an entity is spawned it move towards the player and follows them forever or til they are killed, etc.

I was looking at the tween.js stuff but notice it tweens between two static positions. Or maybe I’m reading this wrong. Can someone lend some advice on this?

-AJ

What you are talking about is commonly known as the “seek” steering behavior. It can be implemented in kinematics or dynamics. Google search “kinematic seek”, you’ll find what you need. You can start by checking this out: https://web.cs.ship.edu/~djmoon/gaming/gaming-notes/ai-movement.pdf

1 Like

Check this vector method, you can lerp between position points in your update loop:

https://developer.playcanvas.com/en/api/pc.Vec3.html#lerp

I came up with a simple solution to my problem

Basically just figure out whether the value of x for the player is either greater or lesser than the value of x of the enemies position then just translate it a value to determine how fast it will close in on the player. I did the same for z and it works well!

The next issue was that when it was perfectly aligned either on the z or x it would constantly jitter. So I would have it check the difference between the player’s x or z value and the enemies x or z value were within a certain range, then stop translation. For instance if it’s between -1 and 1, then don’t move. Run’s smooth as butter now.

Here is the code.

var FollowPlayer = pc.createScript('followPlayer');

FollowPlayer.attributes.add('player',{type:'entity'});
var enemySpeedX = 0.08;
var enemySpeedZ = 0.08;
var minRangeApproach = 15;

FollowPlayer.prototype.update = function(dt) {
    var playerPos = this.player.getPosition();
    var enemyPos = this.entity.getPosition();
    
    if(playerPos.x - enemyPos.x >= -0.1 && playerPos.x - enemyPos.x <= 1){
        
    } else if(playerPos.x >= enemyPos.x){
        this.entity.translateLocal(enemySpeedX,0,0);
    } else if(playerPos.x <= enemyPos.x){
        this.entity.translateLocal(-enemySpeedX,0,0);
    } 
    
    if(playerPos.z - enemyPos.z >= -0.1 && playerPos.z - enemyPos.z <= 1){
        
    } else if(playerPos.z >= enemyPos.z){
        this.entity.translateLocal(0,0,enemySpeedZ);
    } else if(playerPos.z <= enemyPos.z){
        this.entity.translateLocal(0,0,-enemySpeedZ);
    }
    
    if(playerPos.x - enemyPos.x > -minRangeApproach && playerPos.x - enemyPos.x < minRangeApproach){
        enemySpeedX = 0.08;
    } else {
        enemySpeedX = 0.25;
    }
    
    if(playerPos.z - enemyPos.z > -minRangeApproach && playerPos.z - enemyPos.z < minRangeApproach){
        enemySpeedZ = 0.08;
    } else {
        enemySpeedZ = 0.25;
    }

};

I will check what you guys sent though I haven’t checked just yet! Thanks

1 Like