unity3d教程:双摇杆设计思路
更新:HHH   时间:2023-1-7


unity3d教程:双摇杆设计思路

using UnityEngine;
using System.Collections;
   
public enum JoyStickType
{
leftJoyStick,
rightJoyStick
}
   
public class JoyStick : MonoBehaviour {
public JoyStickType joyStickType;//摇杆类型,左摇杆还是右摇杆
public Vector2 centerPos;//摇杆的中心点位置,世界坐标
public Transform centerBall;//摇杆中心球
public float joyStickRadius;//摇杆的半径,世界空间中的半径
private int lastFingerID = -1;//最后一次触摸的手指id
private bool centerBallMoving = false;//摇杆中心球移动开关
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
JoyStickController();
}
void JoyStickController()
{
int count = Input.touchCount;//获取触摸数量
for (int i = 0; i < count; i++)//逐个分析触摸
{
Touch touch = Input.GetTouch(i);Unity3D教程手册
//将当前的触摸位置屏幕转世界坐标
Vector2 currentTouchPos = new Vector2(Camera.main.ScreenToWorldPoint(touch.position).x, Camera.main.ScreenToWorldPoint(touch.position).y);
Vector2 temp = currentTouchPos - centerPos;//得到方向向量temp(触摸转换后的位置和摇杆)
if (touch.phase == TouchPhase.Began)
{
if (Mathf.Round(temp.magnitude) <= joyStickRadius)//如果方向向量temp的长度没有超出摇杆的半径
{
lastFingerID = touch.fingerId;//记录该触摸的id
centerBallMoving = true;//摇杆中心球移动开关打开
}
}
//若中心球移动开关打开,摇杆中心球就会跟随手指移动。但需要加以限制,当手指触摸没有超出摇杆的圆形区域时,中心球完全跟随手指触摸;
//当手指触摸超出圆形区域时,中心球处于触摸位置和摇杆中心点所形成的方向上并且不能超出半径
if (touch.fingerId == lastFingerID && centerBallMoving)
{
if (Mathf.Round(temp.magnitude) <= joyStickRadius) //如果手指触摸没有超出摇杆的圆形区域,即摇杆半径,摇杆中心球的位置一直跟随手指
{
centerBall.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, Camera.main.WorldToScreenPoint(centerBall.transform.position).z));
}
else
{
temp.Normalize();
   //由于摇杆中心球是在一个平面上移动的,本人做法是中心球位置的z值固定为18,改变x,y值,大家可以视情况做一些修改
centerBall.transform.position = new Vector3((temp * joyStickRadius + centerPos).x, (temp * joyStickRadius + centerPos).y, 18);
}
   
if (temp.x >= 0)//0-180
{
//一下为示例代码:控制旋转方向,主要利用Vector2.Angle(temp, new Vector2(0, 5))得到角度并利用
   //initialization_script.current_player_tank_script.BodyRotation(Vector2.Angle(temp, new Vector2(0, 5)));
}
if (temp.x< 0)//180-360
{
                   //一下为示例代码:控制旋转方向,主要利用Vector2.Angle(temp, new Vector2(0, 5))得到角度并利用
//initialization_script.current_player_tank_script.BodyRotation(-1 * Vector2.Angle(temp1, new Vector2(0, 5)));
}
//控制移动的函数或者控制开火的函数,假设左摇杆控制移动,右摇杆控制开火
   switch(joyStickType)
   {
    case JoyStickType.leftJoyStick:
    //Move();
    break;
    case JoyStickType.rightJoyStick:
    //Fire()
    break;
   }
   //当释放触摸的时候中心球位置重置
if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
{
                         centerBall.transform.position = new Vector3(centerPos.x, centerPos.y, 18);
    // 示例代码,视情况自己添加 initialization_script.current_player_tank_script.CoverRotation(initialization_script.current_player_tank.transform.eulerAngles.y);
          centerBallMoving = false;
lastFingerID = -1;
}
}
}
}
}


返回游戏开发教程...