找回密码
 立即注册
查看: 212|回复: 0

Unity 鼠标键盘预览场景脚本

[复制链接]
发表于 2022-7-18 12:39 | 显示全部楼层 |阅读模式
直接上代码:
/** * ========================================== * FileName: KeyboardMouseHandle.cs * Author:   lijia * CreatTime:7/18/2022 * ========================================== */using UnityEngine;public class KeyboardMouseHandle : MonoBehaviour{    [Header("移动速度")]    public float moveSpeed = 4.0f;    [Header("水平旋转角度")]    public float xSpeed = 250.0f;    [Header("垂直旋转角度")]    public float ySpeed = 120.0f;    [Header("向上旋转最大角度")]    public int yMinLimit = 30;    [Header("向下旋转最大角度")]    public int yMaxLimit = 30;    //旋转角度    private float x = 0.0f;    private float y = 0.0f;    private float y_offset;    void Start()    {        y_offset = transform.position.y;    }    // Update is called once per frame    void Update()    {        //WSAD 移动        Move();        //鼠标右键旋转        Rotation();    }    void Move()    {        float horizontalinput = Input.GetAxis("Horizontal");        //AD方向控制        float Verticalinput = Input.GetAxis("Vertical");        //WS方向控制        transform.Translate(Vector3.right * horizontalinput * Time.deltaTime * moveSpeed);        //控制该物体向侧方移动        transform.Translate(Vector3.forward * Verticalinput * Time.deltaTime * moveSpeed);        //确保Y轴不变(摄像机可能有旋转一定角度)        Vector3 position = transform.localPosition;        position.y = y_offset;        transform.localPosition = position;    }    void Rotation()    {        if (Input.GetMouseButton(1))        {            //Input.GetAxis("MouseX")获取鼠标移动的X轴的距离            x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;            y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;            y = ClampAngle(y, -yMinLimit, yMaxLimit);            //欧拉角转化为四元数            Quaternion rotation = Quaternion.Euler(y, x, 0);            transform.rotation = rotation;        }    }    //角度范围值限定    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);    }}
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-9-22 06:50 , Processed in 0.086959 second(s), 25 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表