本文實(shí)例為大家分享了Unity鍵盤WASD實(shí)現(xiàn)物體移動(dòng)的具體代碼,供大家參考,具體內(nèi)容如下
1首先在場(chǎng)景中建立一個(gè)Capsule,將主攝像機(jī)拖到其物體下。

2.將腳本掛在Capsule物體下,WASD 控制移動(dòng)方向,空格延Y軸向上移動(dòng),F(xiàn)延Y軸向下移動(dòng)
using System.Collections;using System.Collections.Generic;using UnityEngine; public class MoveCam : MonoBehaviour{ private Vector3 m_camRot; private Transform m_camTransform;//攝像機(jī)Transform private Transform m_transform;//攝像機(jī)父物體Transform public float m_movSpeed=10;//移動(dòng)系數(shù) public float m_rotateSpeed=1;//旋轉(zhuǎn)系數(shù) private void Start() { m_camTransform = Camera.main.transform; m_transform = GetComponent<Transform>(); } private void Update() { Control(); } void Control() { if (Input.GetMouseButton(0)) { //獲取鼠標(biāo)移動(dòng)距離 float rh = Input.GetAxis("Mouse X"); float rv = Input.GetAxis("Mouse Y"); // 旋轉(zhuǎn)攝像機(jī) m_camRot.x -= rv * m_rotateSpeed; m_camRot.y += rh*m_rotateSpeed; } m_camTransform.eulerAngles = m_camRot; // 使主角的面向方向與攝像機(jī)一致 Vector3 camrot = m_camTransform.eulerAngles; camrot.x = 0; camrot.z = 0; m_transform.eulerAngles = camrot; // 定義3個(gè)值控制移動(dòng) float xm = 0, ym = 0, zm = 0; //按鍵盤W向上移動(dòng) if (Input.GetKey(KeyCode.W)) { zm += m_movSpeed * Time.deltaTime; } else if (Input.GetKey(KeyCode.S))//按鍵盤S向下移動(dòng) { zm -= m_movSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.A))//按鍵盤A向左移動(dòng) { xm -= m_movSpeed * Time.deltaTime; } else if (Input.GetKey(KeyCode.D))//按鍵盤D向右移動(dòng) { xm += m_movSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.Space) && m_transform.position.y <= 3) { ym+=m_movSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.F) && m_transform.position.y >= 1) { ym -= m_movSpeed * Time.deltaTime; } m_transform.Translate(new Vector3(xm,ym,zm),Space.Self); }}以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選