- Home /
Make a cube rotate in right or left direction randomly
i have a cube which i want to rote right or left on the x axis as shown in the diagram randomly.i have seen the euler angles and the rotation concept and some questions about them but have not found them suitable for my case.my code goes like this
var x:float;
function Start()
{
x=Random.value;
}
function Update()
{
if(x>=0.5)
{
//rotate right
}
if(x<0.5)
{
//rotate left
}
}
so i need the cube to rotate slowly towards right if the value is greater than 0.5 like in the pic attached and similarly for lesser values.Thankyou.
Answer by Addyarb · Apr 28, 2015 at 11:25 PM
Hey there, sorry you're having issues with rotation.
From what I understand, you just want to randomly rotate right or left.
Here's how to achieve that: (not tested)
var rotateRight : bool;
function Start()
{
var randomNumber = Random.Range(0,3); //Generates number between 1 & 2
if(randomNumber > 1)
rotateRight = true;
else
rotateRight = false;
}
function Update()
{
if(rotateRight)
transform.Rotate(Vector3.right * Time.deltaTime);
else
transform.Rotate(Vector3.left * Time.deltaTime);
}
i need to stop it after some rotation at an angle like in the second pic.
You could add a var to keep track of how much you've rotated.
var angleToReach : float;
and decrease that while rotating while checking if its reached yet.
if (angleToReach>0)
{
angleToReach-=Time.deltaTime;//since the default vectors all have the length of 1 using just the deltaTime will work here.
if(rotateRight)
transform.Rotate(Vector3.right * Time.deltaTime);
else
transform.Rotate(Vector3.left * Time.deltaTime);
}
Answer by TreeFish · Apr 29, 2015 at 02:37 AM
Use Rotate with a random range like so:
public float speed = 10f; //set your speed
Vector3 randomXDirection = new Vector3(Random.Range(-359, 359),0,0);
void Update (){
transform.Rotate(randomXDirection, speed * Time.deltaTime);
}
Answer by Chris333 · Apr 28, 2015 at 11:39 PM
Hi,
that works i tested it.
#pragma strict
var x:float;
var speed:float = 2.0f;
function Start()
{
x=Random.value;
}
function Update()
{
if(x>=0.5)
{
//rotate right
transform.Rotate(-speed * Time.deltaTime, 0, 0);
}
if(x<0.5)
{
//rotate left
transform.Rotate(speed * Time.deltaTime, 0, 0);
}
}
Ooops, meant to write rotate. Good catch! I'm glad it works though. I'll update my code.
Is that what you wanted to achieve, though?
yes but how do i stop it after some time at a certain angle like in the pic?