How to give NPCs random movement?

54 Views Asked by At

I'm making a PICO-8 game that has 3 separate NPCs. I want to give each one a movement system so that when they move, they choose a random place on the screen, go towards it, and upon reaching it, choose a new random spot and head towards that; rinse and repeat.

Someone told me that I should use the Euclidean Distance Formula to make them (an NPC) move towards a spot, and then calculate their movement based on that, which I tried to do, but I'm nowhere near as advanced as them, so I'm not able to implement this on my own.

This is everything I have for movement so far:

function cleric_movement()
        cleric_dx = rnd(2) - 1
        cleric_dy = rnd(2) - 1
        
        cleric_target_x = rnd(128)
        cleric_target_y = rnd(128)

        d = sqrt((cleric_target_x - cleric_c)^2 + (cleric_target_y - cleric_y)^2

        cleric_x += sgn(cleric_dx)
        cleric_y += sgn(cleric_dy)
        
        cleric_stop_at_edge()
end

function cleric_stop_at_edge()
  if (cleric_x<0) cleric_x=0
  if (cleric_x>111) cleric_x=111
  if (cleric_y<0) cleric_y=0
  if (cleric_y>111) cleric_y=111
end

And just to be clear, each NPC should pick their own target x and y variables!!

Thanks for any help!

P.S. If anyone knows a better place to post a question about PICO-8, since this site doesn't have a lot of PICO questions (31 with this one) and there probably won't be a lot of people familiar with it, please tell me where I can bring this.

1

There are 1 best solutions below

3
Andy On

I would generate the target location like this:

  1. Choose an angle, A, between 0 and 360 degrees
  2. Choose a distance, d, that the NPC must travel
  3. Compute the dx and dy values from the angle and distance:
dx = d * cos(A)
dy = d * sin(A)
  1. If the NPC is located at the coordinates (x, y), check whether (x + dx, y + dy) is a valid location on the map:
  • If this is a valid location, then move towards it.
  • If this is not a valid location, then attempt to generate a new target location.

This algorithm has the advantage of keeping the walking speed constant and reasonable for the NPCs.

If an NPC gets backed into a corner, then they might have to reroll their target location several times, but they will get out almost immediately.