Joystick movement (491566)

I’m using Penelope’s Joystick.js script as a base. The problem is that the Joystick movement is squared instead of rounded.

I’ve tried to fix it with this code:

// Get a value between -1 and 1
position.x = ( gui.pixelInset.x + guiTouchOffset.x - guiCenter.x ) / guiTouchOffset.x;
position.y = ( gui.pixelInset.y + guiTouchOffset.y - guiCenter.y ) / guiTouchOffset.y;

// Normalize code ;)
var angle : float;
angle = Mathf.Atan(position.y/position.x);
position.x = Mathf.Cos(angle);
position.y = Mathf.Sin(angle);

// Adjust for dead zone

Now the input is normalized between -1,1, but the displacement of the graphics is still the same shape.

Any idea about how to fix it?

Cheers!

position = Vector2.ClampMagnitude(position, 1.0f);

Thanks for the code, but what I want is the joystick to be constraint within a circle, not within a square.

Any idea?

That should work just fine. It makes the maximum distance away from the center 1.0; a radius.

Perhaps you’re drawing your joystick based on the touch position and not the actual normalized position?

That it’s not working, because your code makes exactly the same than mine. The problem is that the guiBoundary defined is a square not a cycle.

I’ve found some people trying to solve this, but nobody made it successful:

I’ve modified that part of the code and it’s working, but only in half screen. If anybody can help…

if ( lastFingerId == fingerID )
				{	
				// Override the tap count with what the iPhone SDK reports if it is greater
				// This is a workaround, since the iPhone SDK does not currently track taps
				// for multiple touches
				if (Application.platform == RuntimePlatform.IPhonePlayer)
				{
					if ( touch.tapCount > tapCount )
						tapCount = touch.tapCount;
				}

				if ( touchPad )
				{	
					// For a touchpad, let's just set the position directly based on distance from initial touchdown
					position.x = Mathf.Clamp( ( touchPosition.x - fingerDownPos.x ) / ( touchZone.width / 2 ), -1, 1 );
					position.y = Mathf.Clamp( ( touchPosition.y - fingerDownPos.y ) / ( touchZone.height / 2 ), -1, 1 );
				}
				else
				{						
					// Change the location of the joystick graphic to match where the touch is
					myx = Mathf.Clamp( guiTouchPos.x, guiBoundary.min.x, guiBoundary.max.x );					
					myy = Mathf.Clamp( guiTouchPos.y, guiBoundary.min.y, guiBoundary.max.y );						
					angle = Mathf.Atan((myy-30)/(myx-30));
					
					if ( Mathf.Pow(myx-30,2)+ Mathf.Pow(myy-30,2) > Mathf.Pow(50, 2))
					{
						//var angle : float;				
						//angle = Mathf.Atan(myy/myx);
						gui.pixelInset.x= (Mathf.Cos(angle)*50)+30;
						gui.pixelInset.y = (Mathf.Sin(angle)*50)+30;
					}
					else
					{
						gui.pixelInset.x = myx;
						gui.pixelInset.y = myy;					
					}
					
				}

PD: I’m using joystick.js default script.