Log In  

Hello. I was thinking on how can I make enemy AI the simplest way?
I was looking on YouTube but most of the tutorials are hard to understand.
I am a beginner when it comes to pico 8, so if anyone can help I would greatly appreciate it.

P#139691 2024-01-06 04:11

5

The most basic enemy "AI" would probably be one that just moves directly toward the player. We can do this in the _update loop with something like:

 if (playerx < enemyx) enemyx-=1
 if (playerx > enemyx) enemyx+=1
 if (playery < enemyy) enemyy-=1
 if (playery > enemyy) enemyy+=1

However, if you use a map with collision, you will still need to account for tile collision for your enemies or they will fly right over the map.

I have revised the previous example cart to include a single enemy with the above very basic movement style, and using the same collision logic as we were using for the player. Note that we are able to extend the same logic to both by taking the very clunky if statements we were using (checking points plotted around the player), and moving it into a generic function called hitswall which works on any rectangle (x,y,w,h) and facing (0 is left, 1 is right, 2 is up and 3 is down). I also made a shorthand function fmget for fget(mget(x/8,y/8),0) since this is needed so often.

Cart #koz_enemydemo-0 | 2024-01-06 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA
5


(cc0)

While this is free to use, this is just a barebones demonstration of the principle, it will need to be fleshed out for anything more than basic use cases. For example, with this basic movement style both player and enemy can move ~44% faster on both axes at once (diagonally). The collision is basic as well, anything moving over 1 pixel per frame is going to get.. sticky.

And, obviously, our enemy is not very smart.

Extending this for use with more than one enemy is also a bit of a separate trick. Please don't add ex1,ey1,ew1,eh1,ex2,ey2,ew2,eh2,ex3,ey3,ew3,eh3,ex4..etc! Use a table ;)

Feel free to drop in any questions you might have.

P#139698 2024-01-06 08:05 ( Edited 2024-01-13 18:40)
2

You can use this line of sight function in combination with what kozm0naut said to only let the enemies move when they "see" the player. That feels a little better and also, as a side effect, makes them less prone to get stuck in corners. A second step for that would be storing the last position they saw the player at and moving towards that position instead of towards the player. Maybe make an effort to try to understand that function, although my comments are, admittedly, a little sparse.
But generally I always struggled with fun enemy AI, so if you find something new do not hesitate to share it with us :)

P#139699 2024-01-06 08:39

[Please log in to post a comment]