using UnityEngine;
using System.Collections;
public class CcJoystick : MonoBehaviour
{
public Transform m_Bg;//背景框框
public Transform m_Icon;//小球
float m_fRadius = 100f;//大圆半径
private bool IsDown = false;
private bool IsIn = false;
void Awake()
{
onTouchEnd();
}
void OnPress(bool pressed)
{
if (enabled && gameObject.activeSelf && m_Icon && m_Bg)
{
IsDown = true;
if (pressed)
{
m_Icon.parent.gameObject.SetActive(true);
Vector2 clickPos = Input.mousePosition;
m_Icon.localPosition = new Vector3(clickPos.x, clickPos.y, m_Icon.localPosition.z);
m_Bg.localPosition = new Vector3(clickPos.x, clickPos.y, m_Icon.localPosition.z);
OnDrag(Vector2.zero);
}
else
{
onTouchEnd();
}
}
}
float m_fMoveSpeed = 50f;
public void OnDrag(Vector2 delta)
{
if (enabled && gameObject.activeSelf && m_Icon && m_Bg)
{
Vector2 clickPos = Input.mousePosition;
m_Icon.localPosition = new Vector3(clickPos.x, clickPos.y, m_Icon.localPosition.z);
if (GetRadius() <= m_fRadius)
{
IsIn = true;
}
if (GetRadius() > m_fRadius)
{
//*(大圆半径-小圆半径)
Vector3 toPos = new Vector3((Mathf.Cos(GetRockerDir()) * (m_fRadius - 20)),
(Mathf.Sin(GetRockerDir()) * (m_fRadius - 20)), 0);
m_Bg.localPosition = toPos;//Vector3.Lerp(m_Bg.localPosition, toPos, m_fMoveSpeed);
}
UpdatePlayerMove();
}
}
void UpdatePlayerMove()
{
if (!IsIn || !IsDown || null == m_Bg || null == m_Icon)
return;
fX = (Mathf.Cos(GetRockerDir()) * GetRadius());
fY = (Mathf.Sin(GetRockerDir()) * GetRadius());
//在此处更新玩家位置<span style="font-family: Arial, Helvetica, sans-serif;">即可</span>fX fY 如player.x = fX;
}
private void onTouchEnd()
{
if (null == m_Icon || null == m_Bg)
return;
m_Icon.parent.gameObject.SetActive(false);
IsIn = IsDown = false;
m_Icon.localPosition = m_Bg.localPosition = Vector3.zero;
}
private float GetRockerDir()
{
return Mathf.Atan2(m_Icon.localPosition.y - m_Bg.localPosition.y, m_Icon.localPosition.x - m_Bg.localPosition.x);
}
private float GetRadius()
{
return Mathf.Sqrt(Mathf.Pow((m_Icon.localPosition.x - m_Bg.localPosition.x), 2) +
Mathf.Pow((m_Icon.localPosition.y - m_Bg.localPosition.y), 2));
}
void OnDestroy()
{
onTouchEnd();
}
}