- Home /
Moving GameObject to various position ?
Hello
I have a gameobject that I want to move to various position in scene like a pinball. The GameObject is a balloon and I want to move left, right, top and down randomly in scene.
How can I do this ?
Comment
Answer by Itaros · Oct 28, 2014 at 03:05 AM
Obviously, start by creating a script. You can change position of an object by performing:
private Vector3 moveVector;
void Update(){
moveVector = Vector3.up;
transform.Translate(moveVector*Time.deltaTime);
}
where by "moveVector = Vector3.up" you set where to move.
private float refreshCooldown;
private const float maxCooldown=1F;
private Vector3 moveVector;
void Start(){
moveVector=Vector3.zero;
}
void Update(){
refreshCooldown-=Time.deltaTime;
if(refreshCooldown<0F){
moveVector.x = Random.Range(-1F,1F);
moveVector.y = Random.Range(-1F,1F);
moveVector.z = Random.Range(-1F,1F);
refreshCooldown=maxCooldown;
}
transform.Translate(moveVector*Time.deltaTime);
}
That way it will go in absolutely random direction with changing it each second.
Btw, you can use Random.insideUnitSphere too but I have no idea how hard it is on allocations.