20 Unity 滚动的小球

总结摘要
20-Unity-滚动的小球

用一个项目零基础熟悉 Unity 引擎的基本操作。 开发之旅任重道远,这只是个微不足道开头,最终目标是做出自己的项目来。

个人学习记录,非系统学习,仅记录了对自己有用的东西。

参考课程:b 站 siki 学院 视频链接: https://www.bilibili.com/video/BV15N41177JS/

Unity 中的 Update 方法

查看帧率(即一秒执行多少次 Update 函数)

 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.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Start运行了"); // 日志
    }

    private float updateCount = 0f;
    private float timer = 0f;
    private float updateRate = 0f;

    // Update is called once per frame
    // 每帧执行一次(flush),具体的帧率看电脑性能
    void Update()
    {
        updateCount++;
        timer += Time.deltaTime;

        if (timer >= 1f)
        {
            updateRate = updateCount / timer;
            updateCount = 0f;
            timer = 0f;
        }
    }

    void OnGUI()
    {
        // 每秒调用多少次
        GUI.Label(new Rect(10, 10, 200, 20), "Update Rate:" + updateRate.ToString("F2") + "updates/s");
    }
}

键盘控制

 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public Rigidbody rd; // 定义刚体属性

    // Start is called before the first frame update
    private void Start()
    {
        Debug.Log("Start运行了"); // 日志
    }

    // Update is called once per frame
    // 每帧执行一次(flush),具体的帧率看电脑性能
    private void Update()
    {
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");

        Vector3 dir = new Vector3(h, 0, v);
        rd.AddForce(dir * 3);
    }
}