Hi there,
I’m trying to set up a clock by making variables that I can manipulate through the inspector. However, no matter what I seem to do, I can’t control the hour and minute hands via the variables. The variables WILL change number from 0 while the game is playing, but if I change the numbers, it will revert back instantly to the number it originally was. I’ve tried rotation, localrotation, and eulerAngles to no avail. I feel like I’m missing something basic. What am I doing wrong here?
using UnityEngine;
using System.Collections;
public class clockHandControl : MonoBehaviour {
public float minuteRot;
public float hourRot;
public GameObject hourHand;
public GameObject minuteHand;
// Use this for initialization
void Start () {
minuteRot = 0;
hourRot = 0;
}
// Update is called once per frame
void Update () {
minuteRot = minuteHand.transform.eulerAngles.z * 30;
hourRot = hourHand.transform.eulerAngles.z * 30;
}
}
Your code updates your variables minuteRot and hourRot from the minuteHand and hourHand rotation. I believe you want to do the opposite no? Maybe something like:
void Update () {
minuteHand.transform.eulerAngles = new Vector3(0f, 0f, minuteRot * 6f);
hourHand.transform.eulerAngles = new Vector3(0f, 0f, hourRot * 30f);
}
Be careful as this will set your hands rotation at each update so they will not move anymore. You can easily add some code to make sure this is done only when minuteRot and hourRot change for example (meaning you decided to input different values in the editor).
I like Guidanels soltuion. I haven’t tested it but I believe it would be similar to what you are looking for. I propose the following solution:
void Update()
{
if (hourHand != null)
hourHand.transform.rotation *= Quaternion.AngleAxis(-hourRot * Time.deltaTime, Vector3.forward);
if (minuteHand != null)
minuteHand.transform.rotation *= Quaternion.AngleAxis(-minuteRot * Time.deltaTime, Vector3.forward);
}
Using angle axis with quaternions is a natural way to do what you are attempting to do. hourRot and minuteRot control the rate at which a hand will rotate along its pivot, with the second argument being the axis about which the object rotates, and the first argument being the rate at which it rotates. If you want more clarification let me know, or google around about why quaternions are multiplied Let me know if this helps!