滑动主相机

时间:2019-05-19 16:48:08

标签: c# unity3d touch

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour
{

    public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
    public RotationAxes axes = RotationAxes.MouseXAndY;
    public float sensitivityX = 15F;
    public float sensitivityY = 15F;

    public float minimumX = -360F;
    public float maximumX = 360F;

    public float minimumY = -60F;
    public float maximumY = 60F;

    float rotationY = 0F;

    void Update()
    {
        if (axes == RotationAxes.MouseXAndY)
        {
            float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;

            rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
            rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);

            transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
        }
        else if (axes == RotationAxes.MouseX)
        {
            transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
        }
        else
        {
            rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
            rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);

            transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
        }
    }

    void Start()
    {
        //if(!networkView.isMine)
        //enabled = false;

        // Make the rigid body not change rotation
        //if (rigidbody)
        //rigidbody.freezeRotation = true;
    }
}

我使用脚本来用鼠标旋转相机,并且希望将其转换为触摸方式。我希望我的相机仅在触摸屏幕时旋转。该游戏具有第一个玩家控制器。请帮我把它做成触摸屏

1 个答案:

答案 0 :(得分:0)

获取第一个Touch,然后使用touch.deltaPosition查找自上次更新以来触摸已移动了多少。然后,您可以根据屏幕大小和灵敏度进行缩放。

void Update()
{
    if(Input.touchCount > 0) {
        Touch touch = Input.GetTouch(0);
        float turnAngleChange = (touch.deltaPosition.x / Screen.width) * sensitivityX; 
        float pitchAngleChange = (touch.deltaPosition.y / Screen.height) * sensitivityY;

        // Handle any pitch rotation
        if (axes == RotationAxes.MouseXAndY || axes == RotationAxes.MouseY) {
            rotationY = Mathf.Clamp(rotationY+pitchAngleChange, minimumY, maximumY);
            transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0f));
        }

        // Handle any turn rotation
        if (axes == RotationAxes.MouseXAndY || axes == RotationAxes.MouseX) {
            transform.Rotate(0f, turnAngleChange , 0f);
        }
    }
}

作为旁注,即使俯仰旋转实际上是沿rotationY轴的旋转,也可以称之为俯仰旋转x,反之亦然。