- Home /
Duplicate Question
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.
UPDATE: This worked for me. transform.Translate (Vector3.forward Time.deltaTime moveSpeed, Space.Self);
Answer by Tourist · Feb 14, 2017 at 08:17 AM
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.
Answer by VihanAgarwal · Feb 15, 2017 at 07:38 AM
@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?
transform.Translate(transform.forward moveSpeed Time.deltaTime);
The time.deltaTime doesn't make a difference to the rotation. Any other suggestion?
Answer by AmoVires · Feb 15, 2017 at 02:01 PM
You can check what direction is it facing(rotation) and flip/move it accordingly. Or did I understand wrong?
I am rotating it by a random value between -90 and 90. When I move it, it doesn't face the direction it is moving. I am using what @Tourist suggested right now.
Follow this Question
Related Questions
Enemy Is not moving 1 Answer
Enemy Movement Problem! 1 Answer
How to create random movement in 2D 2 Answers
How to change width and color of a 2d sprite within script 1 Answer
2D sprite wavering 0 Answers