Unity3D之空間轉換學習筆記(二):基礎數學

來源:互聯網
上載者:User

標籤:

這期筆記我們專註Unity提供的各種數學相關的類來學習。

時間Time

API文檔地址:http://docs.unity3d.com/ScriptReference/Time.html

時間加/減速

Demo04是一個自由落體的彈性小球從天空落下的一個情境,用於測試下面的樣本所用。

這個效果在遊戲中也比較常用,比如在戰鬥遊戲中,打敗BOSS或我方死亡時都會呈現一種縮時攝影的效果。

我們的指令碼按下空格將會減速10倍的時間,指令碼綁定在攝像機上,代碼如下:

 1 using UnityEngine; 2 using System.Collections; 3  4 public class Demo04Script : MonoBehaviour 5 { 6     void Start() 7     { 8     } 9     10     void Update()11     {12         if (Input.GetKeyDown(KeyCode.A))13         {14             Time.timeScale = 0.1f;15             Time.fixedDeltaTime = 0.002f;16         }17         if (Input.GetKeyUp(KeyCode.A))18         {19             Time.timeScale = 1.0f;20             Time.fixedDeltaTime = 0.02f;21         }22     }23 }

需要注意的是除了修改timeScale之外,還要修改物理運算的fixedDeltaTime,否則在物理類比中會由於間隔過小導致出現跳幀的現象,大家可以注釋掉fixedDeltaTime的代碼運行查看。

隨機數Random

API文檔地址:http://docs.unity3d.com/ScriptReference/Random.html

隨機數比較簡單,就不過多講解了。

數學運算Mathf

API文檔地址:http://docs.unity3d.com/ScriptReference/Mathf.html

平滑過渡變色

Demo05是一個隨機變換顏色的小盒子,用於測試下面的樣本所用。

主要使用到了柏林噪音,具體的代碼如下:

 1 using UnityEngine; 2 using System.Collections; 3  4 public class Demo05Script : MonoBehaviour 5 { 6     public GameObject cube; 7  8     private Material _material; 9     private Vector3 _colorSpace;10 11     void Start()12     {13         _material = cube.GetComponent<Renderer>().material;14 15         _colorSpace = new Vector3(16                 Random.Range(0f, 10f),17                 Random.Range(0f, 10f),18                 Random.Range(0f, 10f)19             );20     }21     22     void Update()23     {24         float r = Mathf.PerlinNoise(Time.time, _colorSpace.x);25         float g = Mathf.PerlinNoise(Time.time, _colorSpace.y);26         float b = Mathf.PerlinNoise(Time.time, _colorSpace.z);27 28         _material.color = new Color(r, g, b);29     }30 }

由於柏林噪音是一種平滑的隨機形式,所以我們的顏色改變也是平滑過渡的,如果使用普通的隨機數則達不到平滑過渡的效果。

工程檔案下載

敬請期待

Unity3D之空間轉換學習筆記(二):基礎數學

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.