本文为大家分享了unity3d实现虚拟按钮控制人物移动的具体代码,供大家参考,具体内容如下
创建image的ui组件,在image下新建一个button按钮。在image 和button上拖进sprite图片
在button按钮上挂载该脚本
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
|
using system.collections; using unityengine; using unityengine.eventsystems; using unityengine.ui; public class myjoystick : monobehaviour, ipointerdownhandler, ipointeruphandler { public canvas canvas; public static float h; //h和v的值传回给player脚本,使得物体移动 public static float v; private bool ispress = false ; //button按钮是否按下 private vector2 touchpos = vector2.zero; //按下的位置 void update() { if (ispress) { recttransformutility.screenpointtolocalpointinrectangle(canvas.transform as recttransform, input.mouseposition, null , out touchpos); //根据canvas和image的rectransform位置相减得出 touchpos += new vector2(427, 299); float distance = vector2.distance(vector2.zero, touchpos); if (distance > 52) { //限制button不能超出image位置(两者位置相减得出52) touchpos = touchpos.normalized*52; transform.localposition = touchpos; } else { transform.localposition = touchpos; } h = touchpos.x / 52; v = touchpos.y / 52; } } //鼠标按下时触发 public void onpointerdown(pointereventdata eventdata) { ispress = true ; } //鼠标按键弹起时触发 public void onpointerup(pointereventdata eventdata) { ispress = false ; transform.localposition = vector3.zero; } } |
在玩家身上挂载控制玩家移动的脚本
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
|
using system.collections; using system.collections.generic; using unityengine; public class playermove : monobehaviour { public float speed = 0.1f; private float h = 0; private float v = 0; void update() { //首先检测虚拟按键有没有移动,没有再选择键盘输入 if (mathf.abs(myjoystick.h) > 0 || mathf.abs(myjoystick.v) > 0) { h = myjoystick.h; v = myjoystick.v; } else { h = input.getaxis( "horizontal" ); v = input.getaxis( "vertical" ); } //玩家位置移动 if (mathf.abs(h) > 0.1 || mathf.abs(v) > 0.1) { vector3 targetdir = new vector3(h, 0, v); transform.position += targetdir * speed; transform.lookat(transform.position+targetdir); } } } |
这样,就能通过按下button来控制玩家移动了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/shenqingyu0605202324/article/details/78440792