Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[Solve] Need help on clamping joystick

Discussion in 'UGUI & TextMesh Pro' started by markunity3d, Jul 22, 2015.

  1. markunity3d

    markunity3d

    Joined:
    Jul 20, 2015
    Posts:
    3
    Hi, I'm using crossplatform joystick and I want to clamp it to it's max range so it will only move in a circular with center pivot.

    joystick.gif

    Here is the code for clamping from standard assets

    Code (CSharp):
    1. public void OnDrag(PointerEventData data)
    2.         {
    3.             Vector3 newPos = Vector3.zero;
    4.  
    5.             if (m_UseX)
    6.             {
    7.                 int delta = (int)(data.position.x - m_StartPos.x);
    8.                 newPos.x = delta;
    9.             }
    10.  
    11.             if (m_UseY)
    12.             {
    13.                 int delta = (int)(data.position.y - m_StartPos.y);
    14.                 newPos.y = delta;
    15.             }
    16.             transform.position = Vector3.ClampMagnitude( new Vector3(newPos.x, newPos.y, newPos.z), MovementRange) + m_StartPos;
    17.             UpdateVirtualAxes(transform.position);
    18.         }
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    as in in the gif above you only want the red filled circle to move around the solid red outline and nowhere within that outline?
     
  3. markunity3d

    markunity3d

    Joined:
    Jul 20, 2015
    Posts:
    3
    yup. can you help me?
     
  4. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    Code (csharp):
    1.  
    2. public void OnDrag(PointerEventData data)
    3. {
    4.     Vector3 newPos = Vector3.zero;
    5.     // assume these are "if there is input"
    6.     if (m_UseX || m_UseY)
    7.     {
    8.         // get direction, normalize it, expand out to radius, add to start position
    9.         newPos = m_StartPos + ((m_StartPos - transform.position).normalized * radius);
    10.     }
    11.    
    12.     transform.position = newPos;
    13.     UpdateVirtualAxes(transform.position);
    14. }
    15.  
    something like that should work... you'll need to provide "radius" variable somewhere, the rest are the same as the Standard asset you posted above
     
    Senshi likes this.
  5. markunity3d

    markunity3d

    Joined:
    Jul 20, 2015
    Posts:
    3
    thanks. but it doesn't move. but someone in unity answer give me this

    Code (CSharp):
    1.  transform.position = (new Vector3(newPos.x, newPos.y, newPos.z)).normalized * MovementRange + m_StartPos;
    thanks again