之前我通过使用InputSystem实现了手机虚拟摇杆控制移动,这篇文章我准备实现手机端的视角移动。
首先先创建一个初始的Vector2(0,0,0),一个保存我们之后视角坐标的Vector2以及我们视角的移动速度
Vector2 view = Vector2.zero;
private Vector2 Look;
public float viewspeed = 0.5f;
然后需要通过手指触屏来判断,当我们把手指放上屏幕时就开始进行位置的检测,利用Touch.deltaPosition获取触摸点在上一帧和当前帧之间的位置变化量
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
float Xview = touch.deltaPosition.x;//只判断第一根手指
float Yview = touch.deltaPosition.y;
view = new Vector2(Xview, Yview);
Look += view * viewspeed;
//Quaternion.AgleAxis(angle:角度,axis:Vector3.right旋转x轴\Vector3.up旋转y轴)
transform.localRotation = Quaternion.AngleAxis(-Look.y, Vector3.right);
transform.parent.localRotation = Quaternion.AngleAxis(Look.x, Vector3.up);
//因为不能同时旋转同一个game Object的x,y,所以我创建了一个空物体充当相机的父辈,旋转
父辈也能达到旋转相机的效果
}
我们的视角的移动其实就是通过旋转相机的x,y轴来实现的。不过这个时候如果联系之前的虚拟摇杆,我们会发现当我们在移动虚拟摇杆的时候也会判断我们视角的移动,因为触摸判断是整个屏幕,这是我们不想看到的,所以得限制视角移动得触摸判断区域,通过Rect绘制一片区域,当我们手指在那片区域移动时不可以移动视角,修改代码如下
public bool canMoveView;//bool变量判断是否在区域内
void View()
{
Vector2 view = Vector2.zero;
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if (touchArea.Contains(touch.position))
{
canMoveView = false;
}
else
{
canMoveView = true;
}
if (canMoveView)
{
//Debug.Log("in");
float Xview = touch.deltaPosition.x;//只判断第一根手指
float Yview = touch.deltaPosition.y;
view = new Vector2(Xview, Yview);
Look += view * viewspeed;
transform.localRotation = Quaternion.AngleAxis(-Look.y, Vector3.right);
transform.parent.localRotation = Quaternion.AngleAxis(Look.x, Vector3.up);
}
}
}
同时为了能方便直观地设置rect区域得位置和大小,使用红线绘制rect
public Color lineColor = Color.red;
private void OnDrawGizmos()
{
// 计算矩形的四个角点
Vector3 topLeft = new Vector3(touchArea.xMin, touchArea.yMax);
Vector3 topRight = new Vector3(touchArea.xMax, touchArea.yMax);
Vector3 bottomLeft = new Vector3(touchArea.xMin, touchArea.yMin);
Vector3 bottomRight = new Vector3(touchArea.xMax, touchArea.yMin);
// 绘制矩形边框线
Debug.DrawLine(topLeft, topRight, lineColor);
Debug.DrawLine(topRight, bottomRight, lineColor);
Debug.DrawLine(bottomRight, bottomLeft, lineColor);
Debug.DrawLine(bottomLeft, topLeft, lineColor);
}
这样就实现了手机端触屏移动视角