1. 程式人生 > >用UGUI制作可根據手指位置自動定位的隱形遙桿

用UGUI制作可根據手指位置自動定位的隱形遙桿

手遊 color get transform 遇到的問題 透明 child 屏幕上滑 註意

之前寫過遙桿怎麽做,這裏依然用的是之前的方法,就不介紹了。

之前玩過《蠟燭人》,發現手遊版的《蠟燭人》的遙桿是看不見的,手指直接在屏幕左邊滑動人物就可以移動,可能是為了增強沈浸感。最近在寫2D遊戲所以就想來實現一下。

大概思路:

1. 把遙桿UI的GetComponent<Image>().color的透明度改為0;

2.手指落到哪裏就修改搖桿的位置在哪裏。

顯示隱藏搖桿和自動定位的代碼(下面的代碼掛在搖桿上)如下:

public void Hide()
    {
        // 因為繼承了ScrollRect的緣故在編輯器模式下也會執行Update代碼?
        viewport.GetComponent<Image>().color *= new
Color(1, 1, 1, 0); // 透明度改為0,用乘法 content.GetComponent<Image>().color *= new Color(1, 1, 1, 0); } public void Show() { viewport.GetComponent<Image>().color += new Color(0, 0, 0, 1); // 透明度改為1,用加法 content.GetComponent<Image>().color += new Color(0, 0, 0, 1); }
public void AutoSetPosition(Vector2 screenPos) // 設置BG的位置 { // 如果采用自動定位的方式,就一定要讓stick跟隨手指 if (Input.mousePosition.x < Screen.width / 2) content.localPosition = ScreenPosToLocalPos(transform.GetChild(0).GetChild(0).GetComponent<RectTransform>(), Input.mousePosition); //
transform.GetChild(0).GetChild(0)指的是stick(桿) if ((!Input.GetMouseButton(0) || Input.GetMouseButtonDown(0)) && screenPos.x < Screen.width / 2) // Input.GetMouseButton(0)在移動端指單指按下(無意中發現的),手指在屏幕上滑動時,遙桿不跟隨手指,只有桿跟隨 { transform.GetChild(0).localPosition = ScreenPosToLocalPos(GetComponent<RectTransform>(), Input.mousePosition); ; // 註意是LocalPosition } } private Vector2 ScreenPosToLocalPos(RectTransform rt, Vector2 pos) { Vector2 localPoint; RectTransformUtility.ScreenPointToLocalPointInRectangle(rt, pos, null, out localPoint); return localPoint; }

遇到的問題:

1. 一開始我發現手放屏幕上後立即拖動不能拖動stick,因為是先放手,搖桿後根據手定位到手的位置的,所以不能觸發拖動事件,所以我就加入了在手機按下時讓桿跟隨手指移動的代碼,在上面有體現。

 

用UGUI制作可根據手指位置自動定位的隱形遙桿