Unity3D_游戏物体随着鼠标转动

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

public class GunManager : MonoBehaviour
{
    //规定 最大X轴的旋转
    public float maxXRoutation = 70;
    //规定 最小X轴的旋转
    public float minXRoutation = 0;
    //规定 最大Y轴的旋转
    public float maxYRoutation = 50;
    //规定 最小Y轴的旋转
    public float minYRoutation = 0;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

        //获取屏幕鼠标屏幕的位置 0-1之间 从左到右
        float xMouse = Input.mousePosition.x / Screen.width; 
        //获取屏幕鼠标屏幕的位置 0-1之间 从上到下
        float yMouse = Input.mousePosition.y / Screen.height;

        //限定值的范围
        //Mathf.Clamp(yMouse * maxXRoutation, minXRoutation, maxXRoutation)
        //Mathf.Clamp(要限定的值, 最小值范围, 最大值范围)
        //如果要限定的值 在minXRoutation到maxXRoutation 之间就返回
        float xAngle = Mathf.Clamp(yMouse * maxXRoutation,minXRoutation,maxXRoutation) - 20;
        float yAngle = Mathf.Clamp(xMouse * maxYRoutation, minYRoutation, maxYRoutation) - 200f;
        //设置枪的欧拉角 Gun枪的旋转
        transform.eulerAngles = new Vector3(-xAngle,yAngle,0);
    }
}

实现效果:

猜你喜欢

转载自blog.csdn.net/weixin_42137574/article/details/106232469