GUI Joy Stick move along arc?

Original Question:
I want to move my GUI joy stick in a perfect circle, not exceeding defined distance. Here is my code so far, that obviously doesn’t work. How can I modify this to rotate the joy stick position along an arc of defined distance?

Updated Question:
I have updated my code to where the joy stick moves around a circle. However I would like to achieve the same outcome with less code.

var joyStick:Texture; //defined in inspector
var joyRect:Rect;     //defined in inspector
var maxDist:float;   //defined in inspector

private var joyCenter:Vector2;

function Start(){
    joyCenter = joyRect.center;
}

function OnGUI(){
    var event:Event = Event.current;

    if(Input.GetKey(KeyCode.Mouse0)){
        var mousePos:Vector2 = event.mousePosition;
        var horDist:float = Mathf.Pow(mousePos.x-joyCenter.x, 2);
        var vertDist:float = Mathf.Pow(mousePos.y-joyCenter.y, 2);
        var dist:float = Mathf.Sqrt(horDist+vertDist);

        if(dist<maxDist){
            joyRect.center = mousePos;
        }else{
            //Move joyStick around a circle

            var angle:float = Mathf.Atan2(vertDist,horDist);
            var adjustedPos:Vector2;

            adjustedPos.x = joyCenter.x + ( Mathf.Cos(angle)*maxDist );
            adjustedPos.y = joyCenter.y + ( Mathf.Sin(angle)*maxDist );

            joyRect.center = adjustedPos;
        }
    }else{
        joyRect.center = joyCenter;
    }
}

First using Mathf.Pow for the square is just crazy. This function is slow as hell. The Vector3 class has already a Distance() function which you could use.

However it seems that you just want to clamp the magnitude… Well there is also a function for that :smiley:

Vector3.ClampMagnitude

Next thing is using the Input class in OnGUI is not recommended. OnGUI is for processing GUI events and this function is called multiple times per frame. You should use the Event class exclusively in OnGUI.

However i guess it’s better to do that in Update since it isn’t related to GUI at all.

edit fixed the flipped mouse coordinate.

function Start()
{
    joyCenter = joyRect.center;
}

function Update()
{
    if(Input.GetKey(KeyCode.Mouse0))
    {
        var mousePos:Vector2 = Input.mousePosition;
        mousePos.y = Screen.height - mousePos.y;
        var relPos = mousePos - joyCenter;
        relPos = Vector2.ClampMagnitude(relPos, maxDist);
        joyRect.center = joyCenter + relPos;
    }
    else
    {
        joyRect.center = joyCenter;
    }
}