Each hour, the Hours arm has to rotate 360/12 degrees. The Minutes arm has to rotate 360/60 degrees per minute. Finally, the Seconds arm has to rotate 360/60 degrees every second. Let's define these values as private constant floating-point values for convenience.
using UnityEngine;
public class ClockAnimator : MonoBehaviour {
private const float
hoursToDegrees = 360f / 12f,
minutesToDegrees = 360f / 60f,
secondsToDegrees = 360f / 60f;
public Transform hours, minutes, seconds;
void Update() {
// currently do nothing
}
}
Each update we need to know the current time to get this thing to work. The System namespace contains the DateTime struct, which is suited for this job. It has a property called Now that always corresponds with the current time. Each update we need to grab it and store it in a temporary variable.
using UnityEngine;
using System;
public class ClockAnimator : MonoBehaviour {
private const float
hoursToDegrees = 360f / 12f,
minutesToDegrees = 360f / 60f,
secondsToDegrees = 360f / 60f;
public Transform hours, minutes, seconds;
void Update() {
DateTime time = DateTime.Now;
}
}
To get the arms to rotate, we need to change their local rotation. We do this by directly setting the localRotation of the arms, using quaternions. Quaternion has a nice method we can use to define an arbitrary rotation.
Because we're looking down the Z axis and Unity uses a lefthanded coordinate system, the rotation must be negative.
using UnityEngine;
using System;
public class Clock : MonoBehaviour {
private const float
hoursToDegrees = 360f / 12f,
minutesToDegrees = 360f / 60f,
secondsToDegrees = 360f / 60f;
public Transform hours, minutes, seconds;
void Update() {
DateTime time = DateTime.Now;
hours.localRotation = Quaternion.Euler(0f, 0f, time.Hour * -hoursToDegrees);
minutes.localRotation = Quaternion.Euler(0f, 0f, time.Minute * -minutesToDegrees);
seconds.localRotation = Quaternion.Euler(0f, 0f, time.Second * -secondsToDegrees);
}
}
Improving the clock
This works! When in play mode, our clock shows the current time. However, it behaves much like a digital clock as it only shows discrete steps. Let's include an option to show analog time as well. Add a public boolean variable analog to the script and use it to determine what to do in the update method. We can toggle this value in the editor, even when in play mode.
using UnityEngine;
using System;
public class Clock : MonoBehaviour {
For the analog option we need a slightly different approach. Instead of DateTime.Now we'll use DateTime.Now.TimeOfDay, which is a TimeSpan. This allows us easy access to the fractional elapsed hours, minutes, and seconds. Because these values are provided as doubles – double precision floating-point values – we need to cast them to floats.
using UnityEngine;
using System;
public class Clock : MonoBehaviour {