Unity鍵盤WASD實現(xiàn)物體移動
更新時間:2019年02月22日 10:52:05 作者:weixin_38527697
這篇文章主要為大家詳細介紹了Unity鍵盤WASD實現(xiàn)物體移動,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Unity鍵盤WASD實現(xiàn)物體移動的具體代碼,供大家參考,具體內(nèi)容如下
1首先在場景中建立一個Capsule,將主攝像機拖到其物體下。
2.將腳本掛在Capsule物體下,WASD 控制移動方向,空格延Y軸向上移動,F(xiàn)延Y軸向下移動
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoveCam : MonoBehaviour { private Vector3 m_camRot; private Transform m_camTransform;//攝像機Transform private Transform m_transform;//攝像機父物體Transform public float m_movSpeed=10;//移動系數(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)移動距離 float rh = Input.GetAxis("Mouse X"); float rv = Input.GetAxis("Mouse Y"); // 旋轉(zhuǎn)攝像機 m_camRot.x -= rv * m_rotateSpeed; m_camRot.y += rh*m_rotateSpeed; } m_camTransform.eulerAngles = m_camRot; // 使主角的面向方向與攝像機一致 Vector3 camrot = m_camTransform.eulerAngles; camrot.x = 0; camrot.z = 0; m_transform.eulerAngles = camrot; // 定義3個值控制移動 float xm = 0, ym = 0, zm = 0; //按鍵盤W向上移動 if (Input.GetKey(KeyCode.W)) { zm += m_movSpeed * Time.deltaTime; } else if (Input.GetKey(KeyCode.S))//按鍵盤S向下移動 { zm -= m_movSpeed * Time.deltaTime; } if (Input.GetKey(KeyCode.A))//按鍵盤A向左移動 { xm -= m_movSpeed * Time.deltaTime; } else if (Input.GetKey(KeyCode.D))//按鍵盤D向右移動 { 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); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C# Winform程序?qū)崿F(xiàn)防止多開的方法總結(jié)【親測】
這篇文章主要介紹了C# Winform程序?qū)崿F(xiàn)防止多開的方法,結(jié)合實例形式總結(jié)分析了C# Winform防止多開相關(guān)操作技巧與使用注意事項,需要的朋友可以參考下2020-03-03