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);

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

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.

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);
            view.addLocal(modelForwardDir.mult(speed * tpf));

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”.