1. 程式人生 > 其它 >unity實現按鍵控制人物移動

unity實現按鍵控制人物移動

在unity開發中我們經常會用到按鍵實現某些功能,如wasd控制人物的移動,具體怎麼實現呢?程式碼如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class KeysMove : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
control();

}
public void control()
{
if (Input.GetKey(KeyCode.W))
{
this.transform.Translate(Vector3.forward);
//gameObject.transform.Translate(0, 0, move, Space.Self);


}
else if (Input.GetKey(KeyCode.S))//按鍵盤s向下移動
{
this.transform.Translate(Vector3.back);
}

if (Input.GetKey(KeyCode.A))//按鍵盤a向左移動
{
this.transform.Translate(Vector3.left);
}
else if (Input.GetKey(KeyCode.D))//按鍵盤d向右移動
{
this.transform.Translate(Vector3.right);
}
}

}