1 Creating a Project
新建项目,移除代码编辑器以外的 package
1.4 Color Space
Edit / Project Settings… then select the Player category and scroll down to the Rendering section in the Other Settings panel. Make sure that Color Space is set to Linear.
把渲染调成线性色彩空间,这是目前的通用做法,但是 Unity 默认使用伽马色彩空间。
2 Building a Simple Clock
新建空物体 Clock,制作圆柱体钟面 Face 作为其子物体,旋转为(90, 0, 0),缩放为(10, 0.2,10)。
2.4 Twelve Hour Indicators
制作 12 点指示 Hour Indicator 12,Set its X scale to 0.5, Y scale to 1, and Z scale to 0.1,set its X position to 0, Y position to 4, and Z position to −0.25. Also remove its BoxCollider
component.
新建材质 Hour Indicator,改变颜色为 494949,赋给 Hour Indicator 12。
制作 Hour Indicator 1,Set its X position to 2, its Y position to 3.464, and its Z rotation to −30. Then duplicate that one for hour 2, swap its X and Y positions, and double its Z rotation to −60.
继续制作复制品,调整参数直至制作完 12 个指示物。
2.5 Creating the Arms
Again duplicate Hour Indicator 12 and name it Hours Arm. Then create a Clock Arm material and make the arm use it. In this case I made it solid black, hexadecimal 000000. Decrease the arm’s X scale to 0.3 and increase its Y scale to 2.5. Then change its X position to 0 and its Y position to 0.75 so it points towards hour 12, but also a bit in the opposite direction.
新建空物体 Hours Arm Pivot 作为 Hours Arm 的父物体,来让其绕钟面中心而不是自己的中心旋转。
复制并重命名,制作出 Minutes Arm Pivot 和 Seconds Arm Pivot。
Minutes Arm should be narrower and longer than Hours Arm, so set its X scale to 0.2 and Y scale to 4, then increase its Y position to 1. Also change its Z position to −0.35 so it sits on top of the hours arm.
Adjust Seconds Arm as well. This time use 0.1 and 5 for the XY scale and 1.25 and −0.45 for the YZ position.
给秒针建立新的材质,颜色为 B30000
3 Animating the Clock
Clock.cs 代码如下:
using System;
using UnityEngine;
public class Clock : MonoBehaviour // UnityEngine.MonoBehaviour
{
const float hoursToDegrees = -30f, minutesToDegrees = -6f, secondsToDegrees = -6f;
[SerializeField] // 可在 Inspector 窗口中查看,但保持 private
// default 默认初始化
Transform hoursPivot = default, minutesPivot = default, secondsPivot = default;
private void Update()
{
TimeSpan time = DateTime.Now.TimeOfDay; // 可以使用 var 让编译器自动确定类型
// time.TotalHours 是 double 类型
// 如果只需要得到整数的小时 分钟 秒,用 DateTime.Now
hoursPivot.localRotation = Quaternion.Euler(0f, 0f, hoursToDegrees * (float)time.TotalHours);
minutesPivot.localRotation = Quaternion.Euler(0f, 0f, minutesToDegrees * (float)time.TotalMinutes);
secondsPivot.localRotation = Quaternion.Euler(0f, 0f, secondsToDegrees * (float)time.TotalSeconds);
}
}