- Home /
Moving an Enemy randomly
Well, my game is a 2D game, the concept is when the enemies touches the player the game is over. But my problem is I can't make the enemies move on their own at random and when they hit the wall they bounces off to another direction. i'm still new to unity and coding I would greatly appreciate it if any of you could help me out
Answer by FM-Productions · Jun 03, 2017 at 01:21 PM
I think the basic idea would be to calculate a random direction, move the enemy a certain amount of time in this direction and after that time, recalculate the random direction. You can have a more complex movement pattern, but this should suffice for the start.
So, if a certain time is over or if the enemy hit the wall, change the random movement direction. Apply the direction in in relation to the passed time since the last frame. I haven't coded 2D games with unity myself and I haven't tested the code, but this should give you a basic idea:
private float latestDirectionChangeTime;
private readonly float directionChangeTime = 3f;
private float characterVelocity = 2f;
private Vector2 movementDirection;
private Vector2 movementPerSecond;
void Start(){
latestDirectionChangeTime = 0f;
calcuateNewMovementVector();
}
void calcuateNewMovementVector(){
//create a random direction vector with the magnitude of 1, later multiply it with the velocity of the enemy
movementDirection = new Vector2(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f)).normalized;
movementPerSecond = movementDirection * characterVelocity;
}
void Update(){
//if the changeTime was reached, calculate a new movement vector
if (Time.time - latestDirectionChangeTime > directionChangeTime){
latestDirectionChangeTime = Time.time;
calcuateNewMovementVector();
}
//move enemy:
transform.position = new Vector2(transform.position.x + (movementPerSecond.x * Time.deltaTime),
transform.position.y + (movementPerSecond.y * Time.deltaTime));
}
In OnCollisionEnter2D or whatever collision function you are using, you can then check, if the enemy hit a wall, if so, calculate a new movement direction. You could check for the wall by assigning a tag to the wall objects and compare the tags. If the gameObject of your collider has the tag "wall" you can then call the calcuateNewMovementVector() function again.
Answer by salmisifofedz · Jun 24, 2021 at 02:34 PM
@HyPnOj64 I think u should add screen boundaries, because this script will make ur object move out of the screen
Your answer
Follow this Question
Related Questions
problem extracting transform from an array 1 Answer
Enemy Nudging Towards Player 1 Answer
Unity2D Animation issues 1 Answer
Doing a flocking algorithm 0 Answers