El joystick es en realidad bastante simple. Solo necesitas un personaje objetivo a controlar y la dirección para controlar su movimiento. Simplemente llama a la función de movimiento del personaje: estoy
pasando el ángulo utilizado, basado en la dirección actual de avance de la cámara = hacia arriba joystick El ángulo entre la dirección y el vector actual del joystick hacia el centro Rotación: Un poco alrededor: Como se muestra en la figura
//isDown是一个bool变量,记录是否正在使用摇杆
if (Input.GetMouseButtonDown(0))
{
//这个是我自定义摇杆的触碰范围:是一个rect矩形,返回的是否在这个屏幕范围触碰的屏幕
isDown = App.Instance.chickInRect(mouPos);
}
if (Input.GetMouseButtonUp(0))
{
isDown = false;
}
moveDir = Vector2.zero;
angle = 0;
//得到ui在屏幕上面的坐标---当前摇杆底图中心pos
Vector2 img_ygbg_pos = RectTransformUtility.WorldToScreenPoint(App.Instance.uiCamera, img_ygbg.position);
//得到ui在屏幕上面的坐标--当前摇摇动的图片中心pos
Vector2 img_ygzx_pos = RectTransformUtility.WorldToScreenPoint(App.Instance.uiCamera, img_ygzx.position);
Vector2 imgpos = Vector2.zero;
float dis = 0;
if (isDown)
{
if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0))
{
Debug.Log("这是遥感范围");
Vector2 pos = Input.mousePosition;
dis = Vector2.Distance(pos, img_ygbg_pos);
//限制摇杆最远距离rac=55
dis = Mathf.Clamp(dis, 0, rac);
moveDir = pos - img_ygbg_pos;
imgpos = img_yzbg_2dpos + moveDir.normalized * dis;
img_ygzx.localPosition = imgpos;
}
}
//如果没有点击,坐标进行重合,相当于没有移动值
else
{
img_ygzx.localPosition = img_ygbg.localPosition;
}
//角色速度重置
App.Instance.mine.nowSpeed = 0;
if (moveDir != Vector2.zero)
{
Vector2 forwlordPos = new Vector2(0, 1);
angle = Vector2.Angle(forwlordPos.normalized, imgpos.normalized);
//这个是为了利用叉乘判断角度为负还是为正,以为点乘只有0-180度。。。。
float angledir = Vector3.Cross(new Vector3(forwlordPos.x, 0, forwlordPos.y), new Vector3(moveDir.x, 0, moveDir.y)).y;
angle *= angledir < 0 ? -1 : 1;
if (moveDir.sqrMagnitude > 0.1f)
{
App.Instance.mine.nowSpeed = dis * 0.11f;
//Debug.Log( + "-----");
//将角度和方向传出去
EventManager.DispatchEvent<float, Vector2>(EventName.Instance.MOVETOROLE, angle, moveDir);
}
}
角色里面的旋转角色:
private void Rota(float angle)
{
//当前摄像机
Transform cameraTra = Camera.main.transform;
Vector3 cameraForld = new Vector3(cameraTra.forward.x, 0, cameraTra.forward.z);
//按照角色up轴进行旋转
Quaternion rota = Quaternion.AngleAxis(angle, transform.up);
cameraForld = (rota * cameraForld).normalized;
transform.rotation = Quaternion.LookRotation(cameraForld, transform.up);
}