1091226 長壓住按鈕控制器
by 黃國哲 2020-12-26 11:08:58, 回應(0), 人氣(457)
安裝時將這個腳本拖曳到Image底下,在按鈕選自己這個Image物件
功能選LongPressFunction
原理:
設定一個移動方向的運算子
在按下按鈕的時候會送出一個數字到運算子
update去偵測該運算子的數字,去作出對應方向的移動
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class 腳本按鈕 : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public GameObject controller1 ; //宣告要被遙控的對象
public Text counttext1 ; //宣告要用來辨識方向的運算子
public float PressDownTimer; //按下幾秒觸發
private bool PressDown; //按下
public UnityEvent onLongClick; //開啟Inspector觸發事件
[SerializeField]
public float HoldTime;
//按下按鈕
public void OnPointerDown(PointerEventData eventData){
PressDown = true;
Debug.Log("PressDown");
counttext1.text= "1";
}
//按鈕彈起
public void OnPointerUp(PointerEventData eventData){
Reset();
Debug.Log("PressUp");
counttext1.text= "0";
}
//當按下按鈕 PressDown = true 時計時
void Update(){
if (PressDown == true){
PressDownTimer += Time.deltaTime;
if (PressDownTimer >= HoldTime){
if (onLongClick != null){
onLongClick.Invoke();
}
Reset();
}
}
if(counttext1.text == "1")
controller1.transform.position += new Vector3(0.1f,0,0); //如果運算子為1,往右走
if(counttext1.text == "0")
print(" No Data") ;
}
//當PressUp的時候重製計算時間
private void Reset(){
PressDown = false;
PressDownTimer = 0;
}
//觸發後執行的功能
public void LongPressFuntion() {
Debug.Log("觸發後執行的功能");
}
}
回應