超級簡單之使用CharacterController控制人物移動
阿新 • • 發佈:2018-12-11
使用Input.GetAxis(“Horizontal”) 和 “Vertical”得到垂直和水平方向的值 使用CharacterController.SimpleMove(Vector3)引數表示運動的方向和速度 單位可以認為是 m/s 程式碼如下:
private CharacterController cc; public float speed = 4;
void Start() { cc = GetComponent<CharacterController>(); } void Update() { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); if (Mathf.Abs(h)>0.1f||Mathf.Abs(v)>0.1) { Vector3 targetDir = new Vector3(h, 0, v); transform.LookAt(targetDir+transform.position); cc.SimpleMove(transform.forward * speed); } }
speed 是控制人物移動的速度 float h 獲取的是操縱桿輸入和鍵盤輸入,值為(-1到1)的值,x軸正方向為1,負方向為-1,也就是說A鍵為-1,D鍵為1 float v獲取的是操縱桿輸入和鍵盤輸入,值為(-1到1)的值,y軸正方向為1,負方向為-1,也就是說W鍵為1,S鍵為01 targetDir 是鍵盤輸入之後獲取到的方向,將目標用SimpleMove方法向獲取到方向移動 transform.lookat 是讓目標旋轉到獲取到的方向 transform.forward 是讓目標向正前方移動