- Home /
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;
}
}
Answer by Bunny83 · Apr 01, 2012 at 12:51 AM
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 :D
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;
}
}
Hmm, just realized that Input.mousePosition has it's y coordinate flipped since the origin of the screen is the bottom left, while the GUI has its origin at the top left. Well that means you have to flip it "manually" but i guess it's still better then using OnGUI.
Yeah I got that part... I just wanted less code and better performance