I need to get a random rotation on the Z-axis and then rotate a object to that Z-axis in a set speed, but i have no idea how to do that. Any help would be appreciated. I am using C# btw. .
I tried to do it with a Vector 2 but i could not get that to work with the Z-axis
CodePudding user response:
gameobject.Rotate(x,y,z)
this goes in your update function. gameobject is for the object you want to rotate. x y z are constants you need to set. you can just use the random function to generate a random number. this will rotate your gameobject.
CodePudding user response:
Try something like this:
- In your code, define a variable that allows you to set a speed.
- In your update function, specify the rotation to the object set against Time.DeltaTime. The update function runs every frame, so will execute the rotation at your specified speed.
Time.DeltaTime is used as a way of fine tuning your speed. You could simply set the rotation to the value that you set in step 1, but it's likely to be very fast.
So ...
public float speed = 2.0f;
void Update()
{
var rotation = Time.DeltaTime * speed;
transform.Rotate(new Vector3(0, 0, rotation));
}
I haven't tried it, but even if it doesn't work it should set you on the right path. This code, by the way, assumes that this component is being attached to the object you want to rotate.
I can't remember the proper functionality of the Rotate function so you may need to do this instead:
public float speed = 2.0f;
void Update()
{
var rotation = transform.Rotate;
rotation.z = Time.DeltaTime * speed;
transform.Rotate(new Vector3(0, 0, rotation));
}
The reason Vector2 won't work is because there's only X and Y. Even though you're trying to do 2D, Unity still treats it as a 3D object for transform and rotation purposes, so you have to use a Vector3 to get the Z-axis.