1

I am new to Unity and recently I am struggling with the joystick stuff. I want to change the position of the joystick by finger tap. For example, if I touch the center of the screen, the joystick will show in the center, too.

Here is my code:

private void Update()
{
  Touch firstTap = Input.touches[0];
  if (firstTap.phase == TouchPhase.Began)
  {
    m_StartPos = firstTap.position;
    transform.position = m_StartPos;
    UpdateVirtualAxes(m_StartPos);
  }
  else if (firstTap.phase == TouchPhase.Ended)
  {
    m_StartPos = new Vector3(500f, 500f, 0);
    transform.position = m_StartPos;
    UpdateVirtualAxes(m_StartPos);
  }
}

I add the Update() function in the joystick script. The position does change when I tap the screen but the onGrag() is never called when I move my finger.

derHugo
  • 83,094
  • 9
  • 75
  • 115
jQ Goo
  • 23
  • 5

1 Answers1

1

You can create a class for example JoystricManager, where you'll have an Update() method. In Update() you will check for Input.GetMouseButtonDown(0) - which will be true when user taps the screen. Add a collider to you joystick GameObject and after getting click check if this click is inside the collider. If click is inside - ignore it and just check in your joystick script Input.MousePosition to check movement of joystick itself and do your custom actions (move player, etc). If click will be outside the joystick collider - simply move your joystick to the new position. Save the click position in your joystick to get the beginning coordinate of click. When user will move finger you'll get new mouse position, using this two points you can calculate where your joystick points.

vmchar
  • 1,314
  • 11
  • 15