Unity第一人称手游-左侧控制移动,右侧控制视角和方向(第一人称)
文章最后会附上 项目下载地址
首先实现 IDragHandler 接口
1.移动 和 旋转
public virtual void OnDrag(PointerEventData ped)
{
bool _right = ped.position.x > (Screen.width / 2);
Vector2 pos;
if (!_right)
{
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(imgAnalog.rectTransform, ped.position, ped.pressEventCamera, out pos))
{
pos.x = ((pos.x - (imgAnalog.rectTransform.rect.width / 2)) / imgAnalog.rectTransform.sizeDelta.x);
pos.y = ((pos.y + (imgAnalog.rectTransform.rect.height / 2)) / imgAnalog.rectTransform.sizeDelta.y);
inputVectorAnalogic = new Vector3(pos.x * 2 + 1, 0, pos.y * 2 - 1);
inputVectorAnalogic = (inputVectorAnalogic.magnitude > 1.0f) ? inputVectorAnalogic.normalized : inputVectorAnalogic;
joystickImgAnalog.rectTransform.anchoredPosition = new Vector3(inputVectorAnalogic.x * (imgAnalog.rectTransform.sizeDelta.x / 3), inputVectorAnalogic.z * (imgAnalog.rectTransform.sizeDelta.y / 3));
}
}
else if (_right)
{
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(imgLook.rectTransform, ped.position, ped.pressEventCamera, out pos))
{
pos.x = ((pos.x - (imgLook.rectTransform.rect.width / 2)) / imgLook.rectTransform.sizeDelta.x);
pos.y = ((pos.y + (imgLook.rectTransform.rect.height / 2)) / imgLook.rectTransform.sizeDelta.y);
inputVectorLook = new Vector3(pos.x * 2 + 1, 0, pos.y * 2 - 1);
inputVectorLook = (inputVectorLook.magnitude > 1.0f) ? inputVectorLook.normalized : inputVectorLook;
joystickImgLook.rectTransform.anchoredPosition = new Vector3(inputVectorLook.x * (imgLook.rectTransform.sizeDelta.x / 3), inputVectorLook.z * (imgLook.rectTransform.sizeDelta.y / 3));
}
}
}
2, update 更新数据
void Update()
{
var md = new Vector2(inputVectorLook.z, inputVectorLook.x);
camLook.transform.localRotation = Quaternion.Euler(xyBase.x + md.x * -60, 0, 0);
player.transform.rotation = Quaternion.Euler(0, xyBase.y + md.y * 180, 0);
var md2 = new Vector2(inputVectorAnalogic.z, inputVectorAnalogic.x);
Vector3 forwardMovement = player.transform.forward * md2.x;
Vector3 rightMovement = player.transform.right * md2.y;
charController.SimpleMove(Vector3.ClampMagnitude(forwardMovement + rightMovement, 1.0f) * (Input.GetKey(KeyCode.LeftShift) ? speed * 2: speed));
}
|