一惭等、Transform.Translate移動(dòng),也是最基本的移動(dòng)方式
public float speed = 5;//定義一個(gè)公有有的速度(后面的數(shù)值可以不填办铡,隨后在unity中調(diào)整辞做,默認(rèn)為0)
? ? void Update()
? ? {
? ? ? ? Move();//引用Move代碼
? ? }
? ? void Move()
? ? {
? ? if (Input.GetKey(KeyCode.W)|Input.GetKey(KeyCode.UpArrow))//如果按下W或上箭頭
? {
? ? this.transform.Translate(Vector3.forward * speed * Time.deltaTime);
? ? }
? if (Input.GetKey(KeyCode.S) | Input.GetKey(KeyCode.DownArrow))//如果按下S或下箭頭
{
? ? this.transform.Translate(Vector3.back * speed * Time.deltaTime);
}
? if (Input.GetKey(KeyCode.A) | Input.GetKey(KeyCode.LeftArrow))//如果按下A或左箭頭
? {
? this.transform.Translate(Vector3.left * speed * Time.deltaTime);
? }
? if (Input.GetKey(KeyCode.D) | Input.GetKey(KeyCode.RightArrow))//如果按下D或右箭頭
? {
? this.transform.Translate(Vector3.right * speed * Time.deltaTime);
? }
}
二、Rigidbody(剛體)
? ? public Rigidbody rigid;
? ? public float speed;
? ? /*如果你選擇在Unity里面賦值剛體那以下可以不用做
? ? void start()
? ? {
? ? rigid = GetComponent<Rigidbody>();
}
? ? */
? ? void FixedUpdate()
? ? {
? ? ? ? float horizontal = Input.GetAxis("Horizontal");//左右
? ? ? ? float vertical = Input.GetAxis("Vertical");//前后
? ? ? ? if (Input.GetKey(KeyCode.W)|Input.GetKey(KeyCode.S))
? ? ? ? {
? ? ? ? ? rigid.velocity = Vector3.forward * vertical * speed;
? ? ? ? }
? ? ? ? if (Input.GetKey(KeyCode.A) | Input.GetKey(KeyCode.D))
? ? ? ? {
? ? ? ? ? ? rigid.velocity = Vector3.right * horizontal * speed;
? ? ? ? }
? ? }
? ? 總結(jié)
? ? 以上的forward,back , left料扰,right可以在unity的官方文檔中查找到分別對(duì)應(yīng)前后左右凭豪。
? ? 其中update函數(shù)是每一幀執(zhí)行一遍(start只是開始執(zhí)行一遍),而fixedupdate則是每0.02秒執(zhí)行一次晒杈,Time.deltaTime則是根據(jù)機(jī)型嫂伞、電腦的配置自適應(yīng)幀數(shù),所以拯钻,如果是Update中就需要用Time.deltaTime來優(yōu)化帖努,但FixedUpdate中用Time.deltaTime的話就會(huì)顯得速度很慢。