- Home /
2D Random movement?
I'm trying to make a scene where a non playable character moves, for example, 3 units up, then stops for a sec, and then moves 3 units down, stops again, and then 3 units down, etc.
In other words, I'm trying to write a script that makes an object move a determinated distance with random direction (in the Y axis), stops for a moment, and moves again.
I'm pretty noobie programming in Unity, so any clues would be appreciated.
Oh, and I'm using a 2D environment, just in case.
Answer by robertbu · Mar 18, 2014 at 09:26 PM
You might want to explore coroutines for this kind of repeating functionality with pauses. The following link explains coroutines. It uses C#, but the concepts are the same (and it is simpler to create and use co-routines in Javascript).
http://unitygems.com/coroutines/
Here is a short script that uses coroutines to implement your described movement:
#pragma strict
var pauseTime : float = 1.0;
var moveAmount = 3.0;
var moveSpeed = 1.5;
private var nextPos : Vector3;
function Start() {
MoveAndPause();
}
function MoveAndPause() {
nextPos = transform.position;
while (true) {
nextPos.y += (Random.value < 0.5) ? moveAmount : -moveAmount;
while (transform.position != nextPos) {
transform.position = Vector3.MoveTowards(transform.position, nextPos, Time.deltaTime * moveSpeed);
yield;
}
yield WaitForSeconds(pauseTime);
}
}
Answer by Bovine · Mar 18, 2014 at 08:38 PM
If it is as simple as that, then you have a simple state machine and you would be either moving or waiting, the state would alternate between the two.
If it gets much more complex than this, which it probably will, then you can keep band-aiding states together, or look at some AI fundamentals and something like a behaviour tree, of which there are a couple on the asset store.
You can find more details over on: http://aigamedev.com/ Not everything on there is free, but there's some info, this one is free, but you do need to sign up:
Your answer
Follow this Question
Related Questions
2d obstacle moving up and down question 1 Answer
Random Movement in 2D 2 Answers
How to create random movement in 2d 2 Answers
Random movement direction cycle. 2 Answers
Random Movement : 2d 1 Answer