using UnityEngine;
public class FPSCharachter : MonoBehaviour
{
public float speed = 5f;
void Start()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
Move();
MouseLook();
}
void Move()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 fwd = transform.forward;
Vector3 f = new Vector3(fwd.x, 0, fwd.z).normalized;
Vector3 r = transform.right;
Vector3 move = f * z + r * x;
RaycastHit hit;
if (Physics.Raycast(transform.position, move, out hit, move.magnitude * speed * Time.deltaTime))
{
// 如果碰撞到了边界Collider,则不移动
return;
}
transform.position += move * speed * Time.deltaTime;
}
void MouseLook()
{
float mx = Input.GetAxis("Mouse X");
float my = -Input.GetAxis("Mouse Y");
Quaternion qx = Quaternion.Euler(0, mx, 0);
Quaternion qy = Quaternion.Euler(my, 0, 0);
Quaternion newRotation = transform.rotation * qx * qy;
float angle = newRotation.eulerAngles.x;
if (angle > 180) { angle -= 360; }
if (angle < -180) { angle += 360; }
if (angle > 80)
{
newRotation = Quaternion.Euler(80, newRotation.eulerAngles.y, 0);
}
if (angle < -80)
{
newRotation = Quaternion.Euler(-80, newRotation.eulerAngles.y, 0);
}
// 在旋转摄像机前进行碰撞检测
RaycastHit hit;
if (Physics.Raycast(transform.position, newRotation * Vector3.forward, out hit, Mathf.Infinity))
{
// 如果碰撞到了边界Collider,则不旋转
return;
}
transform.rotation = newRotation;
}
}
Unity例子——第一人称视角的角色控制器_vector3 fwd = transform.forward;-CSDN博客
代码其实就是这篇文章里面的.多加了一个不能触碰碰撞体的限制