using UnityEngine;
using System.Collections;
public class JoyMove : TouchLogicV2
{
public Transform player = null;
public float playerSpeed = 2f, maxJoyDelta = 0.05f;
private Vector3 ojoyPos, joyDelta;
private Transform joyTrans = null;
public CharacterController troller;
void Start ()
{
joyTrans = this.Transform;
ojoyPos = joyTrans.Position;
}
void OnTouchBegan()
{
//need to cache the touch index that started on the joystick
touch2Watch = TouchLogicV2.currTouch;
}
void OnTouchMovedAnywhere()
{
if(TouchLogicV2.currTouch == touch2Watch)
{
//move the joystick
joyTrans.position = MoveJoyStick();
ApplyDeltajoy();
}
}
void OnTouchStayedAnywhere()
{
if(TouchLogicV2.currTouch == touch2Watch)
{
ApplyDeltajoy();
}
}
void OnTouchEndedAnywhere()
{
if(TouchLogicV2.currTouch == touch2Watch)
{
//move the joystick back to its orig position
joyTrans.position = ojoyPos;
touch2Watch = 64;
}
}
void ApplyDeltajoy()
{
troller.Move ((player.forward * joyDelta.z + player.right * joyDelta.x) * playerSpeed * Time.deltaTime);
}
Vector3 MoveJoyStick()
{
float x = Input.GetTouch (touch2Watch).position.x / Screen.width,
float y = Input.GetTouch (touch2Watch).position.y / Screen.height;
Vector3 position = new Vector3 (Mathf.Clamp(x, ojoyPos.x - maxJoyDelta, ojoyPos.x + maxJoyDelta),
Mathf.Clamp(y, ojoyPos.y - maxJoyDelta, ojoyPos.y + maxJoyDelta), 0);
joyDelta = new Vector3 (position.x - ojoyPos.x, 0, position.y - ojoyPos.y).normalized;
return position;
}
}