unity实现手游虚拟摇杆实现手游虚拟摇杆
本文实例为大家分享了unity实现手游虚拟摇杆的具体代码,供大家参考,具体内容如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 绑定到摇杆上的摇杆类,参考半径50
/// </summary>
public class Rocker : MonoBehaviour {
Vector2 m_offet;//偏移向量
Vector2 m_originalPos;//摇杆原始屏幕坐标
Touch[] touches;//屏幕上触控点数组
int touch_Id = -1;//触控点数组下标
bool isMove = false;//是否移动
float m_ScreenScale;
/// <summary>
/// 给外部调用的偏移向量,告知摇杆参数
/// </summary>
public Vector3 Offet
{
get
{
return m_offet;
}
}
// Use this for initialization
void Start () {
m_originalPos = transform.position;//摇杆中心的屏幕坐标位置
m_ScreenScale = Screen.width / 800f;
}
// Update is called once per frame
void Update () {
//得到屏幕触控数组
touches = Input.touches;
if (touches.Length > 0)//如果触点开启
{
//得到离摇杆中心最近的触点下标 touch_Id;
if (touches.Length == 1)//只有一个触点时
{
touch_Id = 0;
}
else if (touches.Length > 1)//触点大于1个时
{
touch_Id = 0;//先假设下标为0
for (int i = 1; i < touches.Length; i++)//遍历触点数组
{
if (Vector2.SqrMagnitude(touches[i].position - m_originalPos) < Vector2.SqrMagnitude(touches[touch_Id].position -
m_originalPos))//第i个点比假设的点近
{
touch_Id = i;//假设的点改为第i个点
}
}
}
//如果得到的触点不是取消或抬起
if (Input.GetTouch(touch_Id).phase != TouchPhase.Canceled && Input.GetTouch(touch_Id).phase != TouchPhase.Ended)
{
//触点在摇杆范围内
if(Vector2.SqrMagnitude(touches[touch_Id].position - m_originalPos) <= 50*50 * m_ScreenScale * m_ScreenScale)//50为背
景半径
{