- Home /
How to set perfect rotation using deltaTime
Hi,
I am fairly new to unity so im sure this is obvious, but here it goes...
I have a set of three cubes that spin along the x axis and stop spinning based off random variables (think poker machine). I figured out i could have them spin to the correct position by simply adding 0,0.25,0.5,0.75 (because they are spinning 360 degrees per second) to my timer but the cubes spin slightly off axis with the code i am using (which accumulates after several spins). How can i set them to have perfect rotation?
function Update () {
if(spinStep != 0) {
timer += Time.deltaTime;
}
if (spinStep == 1) {
spin1.transform.Rotate(360*Time.deltaTime,0,0);
if(timer >= 3 + (0.25 * RESULT1)){
spinStep = 2;
}
}
if (spinStep <= 2 && spinStep != 0) {
spin2.transform.Rotate(360*Time.deltaTime,0,0);
if(timer >= 6 + (0.25 * RESULT2)){
spinStep = 3;
}
}
if (spinStep <= 3 && spinStep != 0) {
spin3.transform.Rotate(360*Time.deltaTime,0,0);
if(timer >= 9 + (0.25 * RESULT3)){
spinStep = 0;
timer = 0;
}
}
}
function OnGUI() {
if(GUI.Button (Rect(Screen.width/2-120,Screen.height-105,240,70), spinText)) {
spinStep = 1;
RESULT1 = Random.Range(0,3);
RESULT2 = Random.Range(0,3);
RESULT3 = Random.Range(0,3);
}
}
Answer by Dave-Carlile · Dec 18, 2012 at 01:19 PM
Try using FixedUpdate instead of Update. FixedUpdate should always run the same number of times. You can configure the frequency in project settings.
You'll probably be better off exercising more precise control over the rotation. You can do this by moving a variable from 0 to 1 over the time you want the cube to rotate n times, and using that value to interpolate the rotation. Try some thing like this...
totalRotation = 5 * 360 // total number of degrees to rotate - e.g. 5 times around in this case
totalTime = 6; // seconds to take to rotate totalRotation degrees
currentRotationTime = 0 // current elapsed time for the rotation
void Update()
{
// what percentage are we toward the goal?
float t = currentRotationTime / totalTime;
// interpolate the number of degrees between 0 and totalRotation, using t
float currentRotationAmount = Mathf.lerp(0, totalRotation, t);
// set the rotation to that number of degrees
spin1.transform.rotation = Quaternion.Euler(currentRotationAmount, 0, 0)
// update elapsed rotation time, making sure it doesn't go over 1
currentRotationTime = Mathf.clamp(currentRotationTime + Time.deltaTime, 0, 1);
}
Your answer
Follow this Question
Related Questions
why I can't change motion in the BlendTree by C#? 1 Answer
Sound not looping properly on device? 2 Answers
Poker Game ... Distribute Card 2 Answers
Machine Learning with AMD Radeon? 0 Answers
How do I rotate on Z axis within a set of constraints?. 2 Answers