Simple 2D Enemy AI

So I am looking to build a simple enemy AI. This is how I want it structured:

  • Spawn in the center of a gameObject with a BoxCollider2D that’s a trigger
  • Move in any direction at a fixed speed.
  • Change direction every x amount of seconds
  • If it hits the trigger, simply flip the rotation.

Spawning/flipping on the trigger shouldn’t be too hard so I am starting by simply getting a 2D sprite to randomly move and then change direction every x seconds. I saw a bunch of tutorials online that were 3D (these used Navmeshes) and some 2D tutorials that move only along one axis.

Does anyone know good resource/tools in Unity that will suit what I want?

Note: I have tried Mathf.PingPong and it sucks for what I want.

Create a script that spawn a game object with your AI script attached.
Create your AI script that :

  • on Start : chooses a direction randomly
  • on Update : monitor the elapsed time since last direction choice made
  • on OnTriggerEnter : flip the current direction

I don’t think you need anything else that your little hands and 10 minutes of your time, or maybe I have mistaken your request.

@Tourist That’s exactly what I wanted. I can easily do the first two. The only issue is I can’t get my player to move in the same direction as it is facing. I have tried transform.Translate(transform.right * moveSpeed); but this doesn’t work. Any help?

You can check what direction is it facing(rotation) and flip/move it accordingly.
Or did I understand wrong?