# Random Enemy Movement in Unity2D Top Down

Updated on July 13, 2018 in
2 on July 12, 2018

Hi Everyone,

First of all i’d like to say that i’m a bit of a noob when it comes to programming, and I can’t figure out how to do the following: I want my Enemy object to first rotate to a random direction (game is top down perspective) and then move in that direction for a designated amount of time.

At the moment I have a script from a tutorial I found on Youtube that moves the enemy in a random direction for a designated amount of time but he doesn’t rotate to look at the direction he is moving, so it doesn’t look good in my game, because the perspective is directly top down, not “kind of” isometric like in the tutorial.

Here is the code i have right now handling his movement if you want to look at it:

private Rigidbody2D myRigidbody;
public float moveSpeed;
private bool moving;
public float timeBetweenMove;
private float timeBetweenMoveCounter;
public float timeToMove;
private float timeToMoveCounter;
private Vector3 moveDirection;
void Start () {

myRigidbody = GetComponent<Rigidbody2D>();
timeBetweenMoveCounter = Random.Range(timeBetweenMove * 0.75f, timeBetweenMove * 1.25f);
timeToMoveCounter = Random.Range(timeToMove * 0.75f, timeToMove * 1.25f);
}
void Update () {
if (moving)
{
anim.SetInteger("EnemyAnimState", 1);
timeToMoveCounter -= Time.deltaTime;
myRigidbody.velocity = moveDirection;
if (timeToMoveCounter < 0f)
{
moving = false;
timeBetweenMoveCounter = Random.Range(timeBetweenMove * 0.75f, timeBetweenMove * 1.25f);
}
} else if (moving == false) {
anim.SetInteger("EnemyAnimState", 0);
timeBetweenMoveCounter -= Time.deltaTime;
myRigidbody.velocity = Vector2.zero;
if (timeBetweenMoveCounter < 0f)
{
moving = true;
timeToMoveCounter = Random.Range(timeToMove * 0.75f, timeToMove * 1.25f);
moveDirection = new Vector3(Random.Range(-1f, 1f) * moveSpeed, Random.Range(-1f, 1f) * moveSpeed, 0f);
}
}
}

Any help would be appreciated!

• Liked by
on July 13, 2018

Without redoing what you have, or changing anything, since you already have a direction the enemy is moving in, you can turn that into a rotation.

Quaternion wanderDirection = Quaternion.Euler(moveDirection);
transform.rotation = Quaternion.Lerp(transform.rotation, wanderDirection, Time.deltaTime);

If you wanted to do it in a way that doesn’t directly modify the transform’s rotation, (and especially since your game is 2d), you could also get the dot product of the rotation and direction, and use that to rotate around the Z- axis.

on July 13, 2018