Unity3D開發——安卓版的虛擬按鍵實現
阿新 • • 發佈:2019-02-20
//////////////////////////////2015/08/22////////////////////////
/////////////////////////////by xbw//////////////////////////////
///////////////////////////環境 unity4.6.1//////////////////
這個呢,是我自己想要的,這個虛擬按鍵呢在網上找了好多外掛,對於人家的遊戲適應的表現能力很好。然而在自己的遊戲中並不適應,更沒法用,思來想去還是自己寫嗎,早就想到了GUI的Button,索性就實現一下吧,先看一下效果圖,
這幾個就是Button,我的遊戲中的按鈕控制角色的移動也比較奇怪,非正常的運動,PC的按鍵對於這個Button的轉換並不容易,先來看看程式碼,左右以及下的指令碼
if (Input.GetKeyDown("left")) { if(lu==2) { transform.Translate(Vector3.left * 18.0f); lu = 1; } if(lu==3) { transform.Translate(Vector3.left * 18.0f); lu = 2; } } if (Input.GetKeyDown("right")) { if(lu==2) { transform.Translate(Vector3.right * 18.0f); lu = 3; } if(lu==1) { transform.Translate(Vector3.right * 18.0f); lu = 2; } }
這是鍵盤控制的左右,我的想法變成button的,這樣呢,一開始我是直接把要實現的程式碼放在了GUI中,後來不管怎麼點角色都不會移動,通過查詢資料,發現這個程式的執行是有順序的,UpDate跟OnGUI差的不是一點半點,先直線UpDate,並且還了解到,UpDate是每一幀都會執行,而OnGUI是沒幾幀執行,這是unity官方的解釋,這樣的話,把角色移動寫在OnGUI中,就不會每一幀都渲染啦,角色就沒有反應了,所以,我把那些程式做了個開關,用開關控制在UpDate中執行,這樣立馬爽了,看一下程式碼
至於那個註釋掉的以及空著的else中的語句在手機上執行是有問題的,之前在電腦上除錯一點問題都沒有,滑鼠點選button角色是能左右的,然而在手機上,卻沒有效果,後來又想到了幾幀執行一次,這樣的話我們不能再else中關閉開關,我們要在角色移動後在UpDate中關閉開關,這樣就好了,至於這個下,我們的角色會下滑,並且是持續的,這樣我們用到了RepeatButton,這個按鈕有著持續的功能,這樣只要一直按著就會一直下滑,至於那個上,同理,這個沒什麼,都一樣的,好了;;;;希望大家互相學習交流,有錯誤或者無法顯現請留言,我會一一回復的,晚安啦baby們if (GUI.Button(new Rect(0, Screen.height * 0.72f, Screen.width * 0.13f, Screen.height * 0.13f), "左")) { open = true; } else { } GUI.DrawTexture(new Rect(0, Screen.height * 0.72f, Screen.width * 0.13f, Screen.height * 0.13f), zuo1); GUI.DrawTexture(new Rect(0, Screen.height * 0.72f, Screen.width * 0.13f, Screen.height * 0.13f), zuo2); if (GUI.Button(new Rect(0, Screen.height * 0.87f, Screen.width * 0.13f, Screen.height * 0.13f), "右")) { open2 = true; } else { //open2 = false; } GUI.DrawTexture(new Rect(0, Screen.height * 0.87f, Screen.width * 0.13f, Screen.height * 0.13f), you1); GUI.DrawTexture(new Rect(0, Screen.height * 0.87f, Screen.width * 0.13f, Screen.height * 0.13f), you2); if (GUI.RepeatButton(new Rect(Screen.width * 0.92f, Screen.height*0.78f, Screen.height * 0.1f, Screen.height * 0.1f), "")) { open3 = true; open4 = true; } else { open3 = false; } GUI.DrawTexture(new Rect(Screen.width * 0.9f, Screen.height*0.75f, Screen.width * 0.1f, Screen.width * 0.1f), xia); GUI.DrawTexture(new Rect(Screen.width * 0.9f, Screen.height*0.75f, Screen.width * 0.1f, Screen.width * 0.1f), xia1);