- Home /
Random Object movement
I am trying to create Bird Hunting type game in 2d environment using Unity 4.3. For which I have to move my bird here and there so that it become difficult to shoot the bird.
For this I want help from you guys. What is the easiest way to achieve this? If you want any more help then I am ready to provide. I think my question is pretty basic but I am new to this engine.
One method available is $$anonymous$$athf.PingPong. Is that help me in current situation?
Answer by gfoot · Jan 15, 2014 at 10:05 AM
One simple way to do this is to make the bird wait a random amount of time and then pick a nearby location to move to; then move there, and loop.
You can do this quite clearly using coroutines, something like this:
public void Start()
{
StartCoroutine(BirdBrain());
}
public IEnumerator BirdBrain()
{
while (true)
{
yield new WaitForSeconds(Random.value * MaxWaitTime);
Vector3 localTarget;
localTarget.x = (Random.value * 2 - 1) * RandomPositionXRange;
localTarget.y = (Random.value * 2 - 1) * RandomPositionYRange;
localTarget.z = (Random.value * 2 - 1) * RandomPositionZRange;
Vector3 targetPosition = transform.position + localTarget;
while (transform.position != targetPosition)
{
yield return null;
transform.position = Vector3.MoveTowards(transform.position, targetPosition, MoveSpeed * Time.deltaTime);
}
}
}
That's just off the top of my head but hopefully illustrates one way to do this, and how obvious the flow can be when you're using coroutines. The most important thing to remember with coroutines is to make sure that every loop either contains a yield statement, or is sure to exit promptly.
Thanks for your reply gfoot. I want to understand these line of code from you.
localTarget.x = (Random.value 2 - 1) RandomPositionXRange; localTarget.y = (Random.value 2 - 1) RandomPositionYRange; localTarget.z = (Random.value 2 - 1) RandomPositionZRange;
Random.value is from 0 to 1; those expressions just covert it to be from -1 to 1 and then multiply by some scale value.
You can ins$$anonymous$$d write Random.Range(-RandomPositionXRange, RandomPositionXRange) and get the same effect.
Thanks for simple explanation. Using this code I got my question's answer.
Answer by siddharth3322 · Jan 16, 2014 at 10:46 AM
This link also become helpful in creating random object movement because in that person also specify the bounds within which object moves.