Unity笔记-时钟代码

学习自这个教程: https://mp.weixin.qq.com/s/QaEZuMRGTf07pml_h1rhxA

首先创造一个表盘

GameObject → 3D Object → Cylinder 创建1个圆柱体

给它加上刻度

GameObject → 3D Object → Cube 创建12个方块

再加上指针

GameObject → 3D Object → Cube 创建3个方块

最后加上脚本让他动起来

效果如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using UnityEngine;

public class Clock : MonoBehaviour
{
const float degressPreHour = 30f;
const float degressPreMinuteSecond = 6f;
public Transform HourArmTransform;
public Transform MinusArmTransform;
public Transform SecondArmTransform;

// 每秒动一次
void makeArmRun()
{
var time = DateTime.Now;
HourArmTransform.localRotation = Quaternion.Euler(0, time.Hour * degressPreHour, 0);
MinusArmTransform.localRotation = Quaternion.Euler(0, time.Minute * degressPreMinuteSecond, 0);
SecondArmTransform.localRotation = Quaternion.Euler(0, time.Second * degressPreMinuteSecond, 0);
}
// 一直都动
void makeArmRunContinuous()
{
var time = DateTime.Now.TimeOfDay;
HourArmTransform.localRotation = Quaternion.Euler(0, (float)time.TotalHours * degressPreHour, 0);
MinusArmTransform.localRotation = Quaternion.Euler(0, (float)time.TotalMinutes * degressPreMinuteSecond, 0);
SecondArmTransform.localRotation = Quaternion.Euler(0, (float)time.TotalSeconds * degressPreMinuteSecond, 0);
}

// Update is called once per frame
void Update()
{
//makeArmRun();
makeArmRunContinuous();

}
}

作者

vear

发布于

2022-01-07

更新于

2022-01-07

许可协议

评论