Move GameObject randomly
newbie here.. i just like to make a simple trial game but i don't know how to move a gameobject randomly around a certain place. and i want it to move to random spot to another. just like blinking to one place to another continouosly. please help. thanks in advance.
Answer by KdRWaylander · Apr 06, 2016 at 09:03 AM
What language are you using ? JS ? C# ?
You want to make a function that will randomly set the transform of your object every N seconds (N being a number you choose)
To call the random function every N seconds, you can use InvokeRepeating in the Start function.
To set a random value to your transform, as you can't directly modify its value, your need to use a temporary Vector3 and a function that returns random values
Exemple (C#):
Vector3 temp = new Vector3(Random.range(-10.6f,10.6f),Random.range(-10.6f,10.6f),Random.range(-10.6f,10.6f));
transform.position = temp;
Which makes full code (C#, N=1, code is to be placed on the gameobject that you wanna move randomly):
void Start () {
InvokeRepeating("SetRandomPos",0,1);
}
void SetRandomPos() {
Vector3 temp = new Vector3(Random.range(-10.6f,10.6f),Random.range(-10.6f,10.6f),Random.range(-10.6f,10.6f));
transform.position = temp;
}
Your answer
Follow this Question
Related Questions
move a cylinder from a script on the player 0 Answers
2D touch - Why is this movement so jittery? 1 Answer
How can i move just one object ? 0 Answers
Move towards with some extras 1 Answer
How to move a GameObject within a Coroutine in C#? 2 Answers