鼠标拖动物体(相机旋转)

2018-05-08  本文已影响0人  Kyle_An

、、、
using UnityEngine;
using System.Collections;
/// <summary>
/// 挂载:脚本挂载到主摄像机上
/// 功能:通过鼠标控制相机旋转、拖动、拉伸
/// </summary>
public class CameraMove : MonoBehaviour
{
//目标物体、高度、距离
public Transform target;
public float targetHeight = 1.7f;
public float distance = 5.0f;
//滚轮的速度和最大、最小距离
public int zoomRate = 40;
public float maxDistance = 20;
public float minDistance = .6f;

//X和Y轴的旋转速度
public float xSpeed = 250.0f;
public float ySpeed = 120.0f;

//限制Y轴的最大、最小角度
public int yMinLimit = 0;
public int yMaxLimit = 80;

[SerializeField]
private  float x = 0.0f;

[SerializeField]
private  float y = 0.0f;


[SerializeField]
private float desiredDistance;

[SerializeField]
private float correctedDistance;

[SerializeField]


 void Start ()
{
    Vector3 angles = transform.eulerAngles;
    y = angles.x;
    x = angles.y;

    desiredDistance = distance;
}
void LateUpdate ()
{
    // 如果目标没有定义,就不要做任何事情
    Move();
}

public void Move()
{
    if (Input.GetMouseButton(0))
    {
        x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
        y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
    }
    
    //限制Y轴范围
    y = ClampAngle(y, yMinLimit, yMaxLimit);

    //设置相机的旋转
    Quaternion rotation = Quaternion.Euler(y, x, 0);
    transform.rotation = rotation;

    // 计算鼠标滚轮的距离
    desiredDistance -= Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * zoomRate * Mathf.Abs(desiredDistance);
    desiredDistance = Mathf.Clamp(desiredDistance, minDistance, maxDistance);

    // 设置摄像机的位置
    Vector3 position = target.position - (rotation * Vector3.forward * desiredDistance + new Vector3(0, -targetHeight, 0));
    transform.position = position;

    //使用鼠标右键或者中间拖动
    TargetCtrl();
}

private static float ClampAngle(float angle, float min, float max)
{
    if (angle < -360)

        angle += 360;

    if (angle > 360)

        angle -= 360;

    return Mathf.Clamp(angle, min, max);

}

private  float camPostion_x;
private  float camPostion_y;
void TargetCtrl(){
    if (Input.GetMouseButton(2)||Input.GetMouseButton(1))
    {
        camPostion_x -= Input.GetAxis("Mouse X") * 0.04f;
        camPostion_y -= Input.GetAxis("Mouse Y") * 0.04f;
        target.localPosition = new Vector3(camPostion_x, camPostion_y,0);
    }
}

}
、、、

上一篇下一篇

猜你喜欢

热点阅读