Unity键盘WASD实现物体移动
来源:本站原创|时间:2020-01-10|栏目:C#教程|点击: 次
本文实例为大家分享了Unity键盘WASD实现物体移动的具体代码,供大家参考,具体内容如下
1首先在场景中建立一个Capsule,将主摄像机拖到其物体下。
2.将脚本挂在Capsule物体下,WASD 控制移动方向,空格延Y轴向上移动,F延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;//移动系数 public float m_rotateSpeed=1;//旋转系数 private void Start() { m_camTransform = Camera.main.transform; m_transform = GetComponent<Transform>(); } private void Update() { Control(); } void Control() { if (Input.GetMouseButton(0)) { //获取鼠标移动距离 float rh = Input.GetAxis("Mouse X"); float rv = Input.GetAxis("Mouse Y"); // 旋转摄像机 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); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
您可能感兴趣的文章
- 01-10Unity3d获取系统时间
- 01-10Unity3D获取当前键盘按键及Unity3D鼠标、键盘的基本操作
- 01-10Unity UGUI教程之实现滑页效果
- 01-10C#使用Protocol Buffer(ProtoBuf)进行Unity中的Socket通信
- 01-10C#在Unity游戏开发中进行多线程编程的方法
- 01-10C#实现可捕获几乎所有键盘鼠标事件的钩子类完整实例
- 01-10C# winform 模拟键盘输入自动接入访问网络的实例
- 01-10C#中Socket与Unity相结合示例代码
- 01-10C#实现JSON解析器MojoUnityJson功能(简单且高效)
- 01-10Unity中C#和Java的相互调用实例代码
阅读排行
本栏相关
- 01-10C#通过反射获取当前工程中所有窗体并
- 01-10关于ASP网页无法打开的解决方案
- 01-10WinForm限制窗体不能移到屏幕外的方法
- 01-10WinForm绘制圆角的方法
- 01-10C#实现txt定位指定行完整实例
- 01-10WinForm实现仿视频播放器左下角滚动新
- 01-10C#停止线程的方法
- 01-10C#实现清空回收站的方法
- 01-10C#通过重写Panel改变边框颜色与宽度的
- 01-10C#实现读取注册表监控当前操作系统已
随机阅读
- 01-10C#中split用法实例总结
- 01-10使用C语言求解扑克牌的顺子及n个骰子
- 01-11ajax实现页面的局部加载
- 08-05织梦dedecms什么时候用栏目交叉功能?
- 01-11Mac OSX 打开原生自带读写NTFS功能(图文
- 01-10SublimeText编译C开发环境设置
- 01-10delphi制作wav文件的方法
- 04-02jquery与jsp,用jquery
- 08-05dedecms(织梦)副栏目数量限制代码修改
- 08-05DEDE织梦data目录下的sessions文件夹有什