本文实例为大家分享了unity键盘wasd实现物体移动的具体代码,供大家参考,具体内容如下
1首先在场景中建立一个capsule,将主摄像机拖到其物体下。
2.将脚本挂在capsule物体下,wasd 控制移动方向,空格延y轴向上移动,f延y轴向下移动
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
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); } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_38527697/article/details/79675188