wasd移动 鼠标旋转方向 空格跳跃 ctrl蹲
先新建空物体player 绑定 characterController和 FirstPersonController组件
然后相机为子物体
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class FirstPersonController : MonoBehaviour
{
public float speed = 5.0f; // 移动速度
public float mouseSensitivity = 2.0f; // 鼠标灵敏度
public float jumpSpeed = 8.0f; // 跳跃速度
public float gravity = 20.0f; // 重力
private CharacterController characterController;
private Vector3 moveDirection = Vector3.zero;
private float rotationX = 0.0f;
private float rotationY = 0.0f;
private Camera playerCamera;
public float crouchHeight = 0.5f; // 蹲下高度
public float normalHeight = 2.0f; // 正常高度
public float crouchSpeed = 2.5f; // 蹲下时的移动速度
private bool isCrouching = false;
void Start()
{
characterController = GetComponent<CharacterController>();
playerCamera = Camera.main;
// 隐藏并锁定光标
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
// 视角旋转
rotationX += Input.GetAxis("Mouse X") * mouseSensitivity;
rotationY -= Input.GetAxis("Mouse Y") * mouseSensitivity;
rotationY = Mathf.Clamp(rotationY, -90, 90);
playerCamera.transform.localRotation = Quaternion.Euler(rotationY, 0, 0);
transform.rotation = Quaternion.Euler(0, rotationX, 0);
// 移动
if (characterController.isGrounded)
{
float moveDirectionY = moveDirection.y;
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= isCrouching ? crouchSpeed : speed; // 如果在蹲下状态则使用蹲下的移动速度
moveDirection.y = moveDirectionY;
if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
// 蹲下功能
if (Input.GetKeyDown(KeyCode.LeftControl))
{
Crouch();
}
if (Input.GetKeyUp(KeyCode.LeftControl))
{
StandUp();
}
// 应用重力
moveDirection.y -= gravity * Time.deltaTime;
characterController.Move(moveDirection * Time.deltaTime);
}
void OnApplicationFocus(bool hasFocus)
{
// 当应用获得焦点时锁定光标
if (hasFocus)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
void Crouch()
{
characterController.height = crouchHeight;
isCrouching = true;
}
void StandUp()
{
characterController.height = normalHeight;
isCrouching = false;
}
}
然后启动游戏就好了