- Home /
Rotate exactly on time
I need to make a cube rotate to the beat for a music video. The song is at 120 bpm.
one phrase consists out of 4 beats so that the phrase is 2 seconds long.
The first beat hits at 0, the second at 0,25, the third at 0,75 and the last at 1.
With only a little bit of math you know that the beats last 0.25, 0.5, 0.25 and 1 seconds.
After every beat the cube has be rotated 90 degrees. I calculated the speed for each rotation.
But with my solution the rotation is not precise because the operation is in the update function, which varies with the frame rate.
It would be the best to stop a little bit when the cube rotated 90 degrees and then rotate it again, but with my solution it gets worse because the times get smaller and the precision worse.
using UnityEngine;
using System.Collections;
public class rotate : MonoBehaviour
{
private float speed1 = 360f;
private float speed2 = 180f;
private float speed3 = 360f;
private float speed4 = 90f;
void Update ()
{
if (transform.rotation.eulerAngles.y < 90f)
{
float dreh1 = Mathf.Clamp(speed1 * Time.deltaTime, 0f, 90f);
transform.Rotate(0, dreh1, 0);
}
if (90 <= transform.rotation.eulerAngles.y & transform.rotation.eulerAngles.y < 180f)
{
float dreh2 = Mathf.Clamp(speed2 * Time.deltaTime, 0f, 180f);
transform.Rotate(0, dreh2, 0);
}
if (180 <= transform.rotation.eulerAngles.y & transform.rotation.eulerAngles.y < 270f)
{
float dreh3 = Mathf.Clamp(speed3 * Time.deltaTime, 0f, 270f);
transform.Rotate(0, dreh3, 0);
}
if (270 <= transform.rotation.eulerAngles.y & transform.rotation.eulerAngles.y < 360f)
{
float dreh4 = Mathf.Clamp(speed4 * Time.deltaTime, 0f, 360f);
transform.Rotate(0, dreh4, 0);
}
}
}
Answer by drew_wiskus · Mar 10, 2017 at 07:03 AM
You're probably going to want to look into fixed update.
void FixedUpdate() {}
From the documentation: https://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html
"This function is called every fixed framerate frame, if the MonoBehaviour is enabled."
//OR: You can do fancy caluclations with Time.time;
private float start_time;
void Start() {
start_time = Time.time;
}
void Update() {
//fancy calculations with start_time vs Time.time;
float current_time_in_song = Time.time - start_time;
}
Your answer
Follow this Question
Related Questions
Rotate Z axis of object to camera 2 Answers
Image Rotate Gallery Snap 0 Answers
rotating player 180 degrees 0 Answers
Rotate around obsolete - missing Rotate overloads??? 2 Answers
Strange rotation pattern. 0 Answers