直接上代码:
/**
* ==========================================
* 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);
}
}
网友评论