摇杆其实挺简单的,只需要一个需要控制的角色target和控制其移动的方向传出去,调用角色的move函数就可以了: 我是传出去使用的角度,基于摄像机当前前方向=摇杆上方向和摇杆当前到中心的向量之间的角度旋转:有点绕:如图所示
//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);
}
|