Recommended reading

  • CSDN home page
  • GitHub open source address
  • Unity3D plug-in sharing
  • Jane’s address book
  • My personal blog
  • QQ group: 1040082875

One, foreword

Meet again ha, today for you to introduce the clock, clock implementation method tutorial.

There are many ways to achieve, here is just to provide an idea, in line with the mentality of throwing bricks to attract jade, hope to learn with everyone.

Two, the effect diagram and source project download

Effect:Source project download:

wwr.lanzoui.com/iA2Ngpivf6f

Three, implementation,

3-1 Scenario construction

Use Cylinder to build a clock face, then use TextMesh to set the number of hours, and finally use Cube of different lengths to make an hour hand, minute hand and second hand.

The first thing to note here is that the hour hand, minute hand and second hand need to be dragged under the corresponding parent to make a prefabricated body, because the code uses the Quaternion.AngleAxis function to rotate around the axis, so if you rotate the needle directly, it becomes a rotation, so you rotate the parent, and the object rotates accordingly. If the parent is set to 0,0,0, the child is rotated around the center.

After the construction, it is shown as the figure below:

3-2 Code implementation

using System;
using UnityEngine;

public class Clock : MonoBehaviour
{
    private GameObject HourHands;/ / hour
    private GameObject MinuteHand;/ / the minute hand
    private GameObject SecondHand;/ / second hand

    void Start()
    {
        HourHands = GameObject.Find("Clock/hour hand");
        MinuteHand = GameObject.Find("Clock/minute hand");
        SecondHand = GameObject.Find("Clock/Second hand");
    }

    void Update()
    {
        TimeSpan time = DateTime.Now.TimeOfDay;
        HourHands.transform.localRotation = Quaternion.AngleAxis(30 * time.Hours, Vector3.up);
        MinuteHand.transform.localRotation = Quaternion.AngleAxis(6 * time.Minutes, Vector3.up);
        SecondHand.transform.localRotation= Quaternion.AngleAxis(6* time.Seconds, Vector3.up); }}Copy the code

That’s right, just a few lines of code:

Four, after the speech

Code is still a continuation of simple style, not to write a line of code

The whole idea is very simple, is to get the current time, and then let the hour hand, minute hand and second hand to the specified Angle.

Suddenly came to mind another case, is the solar system planet revolution and rotation, HMM ~

That’s it. It’s over.