[AddComponentMenu("NGUI/Interaction/Drag Object")] // I dont know if this is needed
public class UIJoystick : MonoBehaviour {
/// <summary>
/// Target object that will be dragged.
/// </summary>
private Transform target; // Child sprite to move around as joystick
public Vector3 scale = Vector3.one;
public float radius = 1f; // the radius for the joystick to move in world coords
public Vector2 position; // value to be read by other classes [x,y] [-1,1]
private Vector3 userInitTouchPos;
private Vector3 thisInitialPosition; // initial position of this transform
private Vector3 currentTouchPosition = Vector3.zero; // temporary Vec3 used to store current position of "touch"
// (actually touch based on delta from OnDrag()
private Transform myTransform; // cache this transform
int currentTouchID = -1; // touch ID of current touch (obviously)
void Awake () {
// cache transform and initial position
myTransform = this.transform;
thisInitialPosition = myTransform.position;
}
public void Start(){
// get child sprite to move around joystick style
target = myTransform.GetChild(0).transform;
}
public void OnPress (bool val) {
if (val) {
// if nothing is touching the joystick currently, set its ID
if(currentTouchID == -1){
currentTouchID = UICamera.currentTouchID;
}
} else {
// on realease, reset all the values
ResetJoystick ();
}
}
public void OnDrag(Vector2 delta){
// if the current touch ID
if(currentTouchID == UICamera.currentTouchID){
// if change in finger motion
if(delta.x > 1f || delta.x < -1f){
// set the currentPosition using delta from drag
currentTouchPosition
= new Vector3
(myTransform
.position.x + delta
.x, myTransform
.position.y + delta
.y, 0f
); }
// get the vetor of the touch with respect to the static original position
Vector3 difference = currentTouchPosition - myTransform.position;
// clamp it to the radius
difference = Vector3.ClampMagnitude(difference, radius);
// I only use the joystic for X-Axis movement, so I adjust the X value with the currentTouchPosition X
target
.position = new Vector3
(myTransform
.position.x + difference
.x, target
.position.y, 0f
);
// set position with the x,y values of the new position
position = difference;
}
}
// called on OnPress(false)
void ResetJoystick () {
// Release the finger control and set the joystick back to the default position
position = Vector2.zero;
target.position = thisInitialPosition;
currentTouchID = -1;
currentTouchPosition = Vector3.zero;
}
}