1-變換組件移動物體
游戲物體與組件.png
這幅圖現(xiàn)在理解還不深刻,先放在這,日后再來補全。
1.1相關(guān)方法
首先要將腳本掛到這個cube上,然后在這個腳本里面編輯。gameObject.getcomponent<Transform>();獲取相關(guān)組件的引用。
假定這個對象為cubeTransform.
這個方法要寫在start()里面,從游戲開始就要獲取到這個組件。
這個方法要返回一個Transform類型的對象。1.2
然后調(diào)用這個對象的Translate方法,
Transform.Translate(Vector3, Space):
兩個參數(shù)
(Vector3)表示三維向量,
向量可以表示一個方向和一個位置。
Space是一個枚舉。
Space.self和Space.World分別表示自身坐標系和世界坐標系。-
2鍵盤控制移動方向。
void Update () { if(Input.GetKey(KeyCode.W)) { _cubeTransform.Translate(Vector3.forward * 1f*Time.deltaTime,Space.Self); } if(Input.GetKey(KeyCode.S)) { _cubeTransform.Translate(Vector3.back * 1f * Time.deltaTime, Space.Self); } if(Input.GetKey(KeyCode.A)) { _cubeTransform.Translate(Vector3.left * 1f * Time.deltaTime, Space.Self); } if (Input.GetKey(KeyCode.D)) { _cubeTransform.Translate(Vector3.right * 1f * Time.deltaTime, Space.Self); }