C#How to make sprite move in a New direction every X seconds,How to change movement direction every X seconds in C#

(C#)Im trying to make an enemy (In 2D) that moves in a new direction every X seconds, but I don’t know how to do this. Any help would be very much appreciated.

Thanks

Heyo,

Well, what part do you not know how to do? Getting a new direction? Performing an action after every X seconds? Both?


GETTING NEW DIRECTION

Well there are a number of ways to pull this part off. One way is to use Random.insideUnitCircle. It’ll give you a random Vector2 pointing in some direction. I’m pretty sure that it has a length of 1, but if not, you could normalize it so you have more control over the vector.


EVENT EVERY X SECONDS

Again, like most things in computer science I suppose, there are a number of ways to do this too. You could:

  1. Have a little variable that you continuously add Time.deltaTime to and when it reaches your X, reset the little counter back to 0 and continue its little cycle.
  2. Alternatively, there is a function called InvokeRepeating which will, well, repeat a function you give it. You can give it a repeat rate and then the amount of time to wait before actually starting the cycle. This will only be called once when you want to actually start the cycle. Perhaps in your Start function? I dunno.

COMBINING

So, if that all makes sense, you’ve got all the pieces to make something neat work here. Using either method for your timer/loop/counter or whatever you want to call it, you will have a little if statement or a function that executes every X seconds. Sooo, you could stick in the bit of code to get a random vector inside of there and poof. You’ll have a random vector every X seconds. Now, it’ll be up to you to decide what to do with that vector. I dunno if you’re using rigidbodies for movement, or translating, or whatever, but yeah. Hopefully that helps. If not, let me know and I can think of something else to throw at ya.