Unity C#和着色器教程 学习笔记(一)

45 阅读1分钟

使用版本2022.3.5f1

基础

时钟

色彩空间

文章推荐在project setting -> Player -> Other settings中将色彩空间改为linear,线性色彩空间。因为unity默认是gamma色彩空间。

仅当您针对旧硬件或旧图形 API 时。OpenGL ES 2.0 和 WebGL 1.0 不支持线性空间,而且在旧移动设备上伽玛可能比线性空间更快。

用新不用旧!为了获得最佳视觉效果。

制作钟表物体

注意做指针时,先制作空物体,并且切换为沿pivot旋转,也就是按这个空物体的几何中心旋转。再将子物体指针放进去。

image.png image.png

显示时间脚本

Quaternion rotation = Quaternion.Euler(0f, 90f, 0f); // 绕Y轴旋转90度

objectName.localRotation = rotation;

Rotation接受一个四元数,旋转特定角度。

// 获取当天此刻的时间

TimeSpan time = System.DateTime.Now.TimeOfDay;

TimeSpan 时间间隔,TimeOfDay获取的是从当天0点到此刻的时间差,也就是获取当天时间。

public class Clock : MonoBehaviour
{
    [SerializeField] 
    public Transform hourPivot, minutePivot, secondPivot;
    // Start is called before the first frame update
    private const float hourDegree = -30;
    private const float minuteDegree = -6;
    private const float secondDegree = -6;
    private void Start()
    {
        Debug.Log("当前时间: " + System.DateTime.Now.TimeOfDay);
    }
    // Update is called once per frame
    void Update()
    {
        // 获取当天此刻的时间
        TimeSpan time = System.DateTime.Now.TimeOfDay;
        hourPivot.localRotation = Quaternion.Euler(0, 0, hourDegree * (float)time.TotalHours);
        minutePivot.localRotation = Quaternion.Euler(0, 0, minuteDegree * (float)time.TotalMinutes);
        secondPivot.localRotation = Quaternion.Euler(0, 0, secondDegree * (float)time.TotalSeconds);
    }
}