This is a question that relates to this post here:
This code is a modification of the default 2d sidescroller joystick included with Unity 3.
I’m trying to accomplish the same thing that the person in that post is (I’m assuming). I’m almost there, but not quite.
By default, the joystick moves inside of a square. An invisible boundary Rect. I’m trying to modify this so that it moves inside that same rect, but is clamped to a circle. So instead of the joystick graphic jamming into corners, we have it moving around the outside of the circle if the user is moving in that direction.
So far, I do have the joystick moving in a circular pattern, but only in the top right-hand portion of the circle. In other words, the center is at 0,0, at the bottom left of the screen. The joystick is moving around that center, but the center should be where the joystick’s default snap-back position is. I can’t for the life of me figure out where in my code it’s getting the 0,0 coordinates from.
Initialization code:
function Start()
{
// Cache this component at startup instead of looking up every frame
joystickGui = GetComponent( GUITexture );
// Store the default rect for the gui, so we can snap back to it
// when player is not touching the joystick
defaultRect = joystickGui.pixelInset;
defaultRect.x += transform.position.x * Screen.width;
defaultRect.y += transform.position.y * Screen.height;
transform.position.x = 0.0;
transform.position.y = 0.0;
defPosition = position;
// This is an offset for touch input to match with the top left
// corner of the GUI
guiTouchOffset.x = defaultRect.width * 0.5;
guiTouchOffset.y = defaultRect.height * 0.5;
// Cache the center of the GUI, since it doesn't change
guiCenter.x = defaultRect.x + guiTouchOffset.x;
guiCenter.y = defaultRect.y + guiTouchOffset.y;
// Let's build the GUI boundary, so we can clamp joystick movement
guiBoundary.min.x = defaultRect.x - guiTouchOffset.x;
guiBoundary.max.x = defaultRect.x + guiTouchOffset.x;
guiBoundary.min.y = defaultRect.y - guiTouchOffset.y;
guiBoundary.max.y = defaultRect.y + guiTouchOffset.y;
}
Broken code under Update()
if ( lastFingerId == touch.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 ( touch.tapCount > tapCount ){
guiTouchPos = Vector2.ClampMagnitude(guiTouchPos,100);
clampedPos.x = Mathf.Clamp(guiTouchPos.x,guiBoundary.min.x,guiBoundary.max.x);
clampedPos.y = Mathf.Clamp(guiTouchPos.y,guiBoundary.min.y,guiBoundary.max.y);
var distance: float=Vector2.Distance(guiCenter,clampedPos);
if(distance<200)
{
joystickGui.pixelInset.x=clampedPos.x;
joystickGui.pixelInset.y=clampedPos.y;
}
}
if ( touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled )
ResetJoystick();
}