Home > Back-end >  is it possible to select and move a on-screen joystick from script?
is it possible to select and move a on-screen joystick from script?

Time:07-04

I try to add a Joystick programmatically by a touch. The prefab with the attached On-Screen Stick gameobject get instantiated and if I release this finger, the gameobject get destroyed. The only problem is, I cannot move the joystick. Is there a way to make the joystick responsible to the finger who instantiated the joystick prefab?

i tried this: but with no luck:

 ExecuteEvents.Execute(leftJoyStick.GetComponent<OnScreenStick>().gameObject, 
                         new BaseEventData(EventSystem.current), ExecuteEvents.selectHandler);

please help.

CodePudding user response:

Ok i'm kinda stupid. i don't need a joystick and do it this way bellow. when i touch the right side of screen i can look around, when i touch the left side of screen i can move around without a static joystick.

private bool hasLeftStick = false;
private Touch joystickLeftToch;
private Vector2 leftStickTouchStartPos;

private bool hasRightStick = false;
private Touch lookFinger;
private Vector2 rightStickTouchStartPos;

// used in Update()
private void ObserveTouches()
{
    foreach (var touch in Input.touches)
    {
        if (Camera.main.ScreenToViewportPoint(touch.position).x > 0.5f)
        {
            if (!hasRightStick)
            {
                hasRightStick = true;
                lookFinger = touch;
                rightStickTouchStartPos = touch.position;
            }
        }
        else
        {
            if (!hasLeftStick)
            {
                hasLeftStick = true;
                joystickLeftToch = touch;
                leftStickTouchStartPos = touch.position;
            }
        }

        if(joystickLeftToch.fingerId == touch.fingerId && touch.phase == UnityEngine.TouchPhase.Moved)
        {
            Vector2 dir = (touch.position - leftStickTouchStartPos).normalized;
            direction = new Vector3(dir.x, 0f, dir.y);
        }

        if (joystickLeftToch.fingerId == touch.fingerId && touch.phase == UnityEngine.TouchPhase.Ended)
        {
            direction = Vector3.zero;
            hasLeftStick = false ;
        }

        if(lookFinger.fingerId == touch.fingerId && touch.phase == UnityEngine.TouchPhase.Moved)
        {                
            look = touch.deltaPosition;
            thridPersonCam.m_XAxis.m_InputAxisValue = look.x;
            thridPersonCam.m_YAxis.m_InputAxisValue = look.y;
        }

        if (lookFinger.fingerId == touch.fingerId && touch.phase == UnityEngine.TouchPhase.Ended)
        {
            look = Vector2.zero;
            thridPersonCam.m_XAxis.m_InputAxisValue = 0f;
            thridPersonCam.m_YAxis.m_InputAxisValue = 0f;
            hasRightStick = false;
        }
    }

    if (Input.touchCount == 0)
    {
        lookFinger.fingerId = -1;
        joystickLeftToch.fingerId = -1;
    }

}
  • Related