本文為大家分享了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