Help With A Follow Me AI

Hi I was hoping some one could help me code an ai for an companion character in my game

thanks for your time
William Boersma


Hi @WilliamBoersma31, take it slow, some questions require more elaborate answers and that requires time by fellow forum members :innocent:

Especially with this question, AI and pathfinding is a broad topic and there isn’t a straightforward answer on how to implement, it depends a lot on your game setting and gameplay.

ok all i need is a simple code where an entity tracks the player and follows it

Sadly there isn’t a Playcanvas API that can do that for you. The closest and simplest example that I can think of is the following. You can work your way and update the code instead of using point and click to drive the entity, to have it automatically move towards the player.

Though note, that isn’t true pathfinding, it won’t avoid obstacles and find paths around them:

If you are building a 2D game or a game that has 2D movement then you can try and use a JS pathfinding library with Playcanvas, like this:

hey would i get the players position

If you mean how you would get the player’s position:

var playerPosition = playerEntity.getPosition();

ok thanks

hey im getting an error when i use that code here is the code that is giving me said error.

var playerEntity =“PLAYER”);
var playerPosition = playerEntity.getPosition();

Are you sure there is an entity that is named PLAYER? Names are case sensitive. Also where do you use that code? And what kind of error are you getting?

yes I am positive. Its telling me root is undefined.

And where do you use it? That means is undefined, most likely you aren’t using it inside a script method.

your right thanks

1 Like

hey @Leonidas the buddy is just sitting and doing nothing can you take a look at the code and see if you can find what i did wrong?,40452185,40452382

hey @Leonidas can you tell me what is wrong with this line of code?


the code causes the game to crash please help @Leonidas
(@DevilZ I’m ating you because you have helped me before)

Can’t find this line in the code editor link sent above? Is this in a different file?

i decided to scrap it but while i have your attention can you help me make an entity play a sound from a script

Study the following samples:

yeah i figured it out