之所以寫這個腳本,是因為我想起了我還是新手的時候,那時為了一個角色控制腳本百度了半天還是一無所獲,因為看不懂啊,都寫的太高級了
希望這個腳本能夠幫助那些 像曾經的我一樣迷失於代碼中的新手們能夠清晰的理解這個角色控制的含義
1 ///角色控制腳本 2 3 public class Player : MonoBehaviour { 4 5 public float m_speed=1; //這個是定義的玩家的移動速度 之所以Public是因為為了方便對其進行調節 (public的屬性和對象會在Unity中物體的腳本選項中顯示出來 前提是你把腳本掛在了物體上) 6 7 void Update () //這個是刷新的意思 以幀為單位的大概每刷新一次1/20秒 8 9 { 10 11 float movex = 0; //這個代表的是玩家在x軸上的移動 12 13 float movez = 0; //這個代表的是玩家在z軸上的移動 14 15 if (Input.GetKey(KeyCode.W)) //這個意思是"當按下W鍵時" 16 17 { 18 19 movez += m_speed * Time.deltaTime; //物體獲得在z軸方向上的增量 也就是向前 20 21 } 22 23 if (Input.GetKey(KeyCode.S)) //按下S鍵時 24 25 { 26 27 movez -= m_speed * Time.deltaTime; //后 28 29 } 30 31 if (Input.GetKey(KeyCode.A)) //A鍵 32 33 { 34 35 movex -= m_speed * Time.deltaTime; //左 36 37 } 38 39 if (Input.GetKey(KeyCode.D)) //D鍵 40 41 { 42 43 movex += m_speed * Time.deltaTime; //右 44 45 } 46 47 this.transform.Translate(new Vector3(movex,0,movez)); //這句代碼是把得到的偏移量通過translate(平移函數)給玩家 從而使得玩家的位置得到改變 48 49 } }
附上玩家的坐標軸 圖中飛機就是玩家 便於理解x軸z軸對玩家移動方向的影響
同時附上Translate函數的聖典介紹:
Transform.Translate 平移
function Translate (translation : Vector3, relativeTo : Space = Space.Self) : void
Description描述
Moves the transform in the direction and distance of translation.
移動transform在translation的方向和距離。
簡單的說,向某方向移動物體多少距離。
If relativeTo is left out or set to Space.Self the movement is applied relative to the transform's local axes. (the x, y and z axes shown when selecting the object inside the Scene View.) If relativeTo is Space.World the movement is applied relative to the world coordinate system.
如果relativeTo留空或者設置為Space.Self,移動被應用相對於變換的自身軸。(當在場景視圖選擇物體時,x、y和z軸顯示)如果相對於Space.World 移動被應用相對於世界坐標系統。
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Update() {
transform.Translate(Vector3.forward * Time.deltaTime);
transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
}