NPC follow character

Hello, im trying to make an NPC follow the character around, as it is now if the player is closer than 3f to the npc it turns to face the player.
But when the player moves further than 3f away it starts moving in the player direction (this is good) but it doesnt rotate or stop when it gets close to the player again.

It’s probably a simple solution that im missing but its gnawing at me badly.

this is the code as is in the custom control for NPC:

protected void controlUpdate(float tpf) {
        Vector3f enemyPos = enemy.getWorldTranslation();
        Vector3f playerPos = player.model.getWorldTranslation();
        
        Vector3f modelForwardDir = enemy.model.getWorldRotation().mult(Vector3f.UNIT_Z);
        walkDirection.set(0,0,0);

        float d = playerPos.distance(enemyPos);
        enemy.control.setViewDirection(playerPos);
        if (d > 3f) {
            enemy.control.setViewDirection(playerPos);
            walkDirection.addLocal(modelForwardDir.mult(speed * tpf));
            enemy.control.setWalkDirection(walkDirection);
        }
        
    
    }

thanks for any replies

You use the player position as the direction, which is not correct. The player position is only the direction when the NPC is at 0/0/0. You have to subtract the NPC position from the player position to get the correct direction from the current position of the NPC.

https://wiki.jmonkeyengine.org/legacy/doku.php/jme3:math_for_dummies

Ah okay thanks for quick answer, will do that.

Math for dummies, perfect!

Forgive my noobness,
from what i understood i have to do something like this:

if (d > 3f) {
            Vector3f view = playerPos.subtract(enemyPos);
            enemy.control.setViewDirection(playerPos);
            view.addLocal(modelForwardDir.mult(speed * tpf));
            enemy.control.setWalkDirection(view);
        } 
        

It now rotates, but as if it was looking at the character from 0,0,0.

By using physicsLocation i got it working now :slight_smile:

In the code you posted setViewDirection should be set to “view”, not “playerPos”.