How do I implement artificial intelligence into my game?

Hello everyone. I am totally new to Defold and would like to implement a simple artificial intelligence system for some of the enemies in my new project. How do I go about doing so, and would you mind sharing some code samples to point me in the right direction? Thank you.

1 Like

Problem is your question doesn’t say what kind of AI you want, what kind of project you want. Different methods of AI can work for different projects better.

Look up finite-state machines / state patterns. You can search finite-state machine + Lua for code examples.

The code here can be adapted to work with Defold.

Behavior trees is another method

Writing some guides for various game AIs is on my todo but not ready yet.

1 Like

Sorry about that. All I want is a simple AI system that consists of the enemy walking back and forth and speeding up when facing a player. Nothing too major. Thanks for the reply regardless.

For that, all you need is a few if statements. Have you tried to implement what you want? Behavior trees would work fine for what you want (but might be overkill), and there are premade libraries you can use.

http://aigamedev.com/open/article/behavior-trees-part1/

1 Like

You shouldn’t try to implement a complex system at this point. Try something like:

  • Let the enemy have a script that keeps track of the direction and speed at which the enemy is moving.
  • On each update():
  • Move the enemy in the current direction and speed.
  • Get the position of the player and compare it to the enemy position and direction.
    • Increase enemy speed if the distance is within some value
    • Reset the enemy speed if the distance is too large or the facing is wrong
3 Likes

Thank you for the resources. I will try it out. For now, I still need to prepare the sprite sheets for my enemies. I’ll hope right into the coding portion immediately afterwards. Thanks again! I truly appreciate it.

1 Like

Ugh! Why didn’t I think of that? Okay great! Thank you for the help, man. I was actually going to try to use two colliders for the enemy game object where one acts as a sort of a… Field of vision, while the other collider is for when the enemy attacks the player. Your method seems to be a lot more cooperative and for that, I thank you for saving me the trouble. Thanks, man.

Thank you both for your quick replies. I’ll notify you of which method worked out for me in the end, but whatever the case may be, I truly appreciate your help! Thanks!

This is also a very good solution. Using one larger collision object of type “trigger” for the field of vision would decouple the enemies from the player even more. Using my suggestion the enemies would need to know the game object id or url to the player to be able to query it for the player position. Using a collision object would remove this required knowledge from the enemy game objects. Try this approach as well!

1 Like