Unity FPS 控制器
FPS(或 第一人称射击游戏)是从第一人称视角控制主角的游戏。
通常的控制方式是 W、A、S 和 D 行走、鼠标查看环顾四周、空格键跳跃、左 Shift 键冲刺,允许玩家在关卡中自由移动。
在这篇文章中,我将展示如何在 Unity 中制作一个 FPS 控制器来处理摄像机旋转和玩家移动。
步骤
要制作 FPS 控制器,请按照以下步骤操作:
- 创建一个新的游戏对象(GameObject -> Create Empty)并命名 "FPSPlayer"
- 创建一个新的胶囊(游戏对象 -> 3D 对象 -> 胶囊)并将其移动到 "FPSPlayer" 对象内
- 从 Capsule 中移除 Capsule Collider 组件,并将其位置改为 (0, 1, 0)
- 将主摄像机移至 "FPSPlayer" 对象内,并将其位置更改为 (0, 1.64, 0)
- 创建个新脚本,将其命名为"SC_FPSController"并将以下代码粘贴到其中:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class SC_FPSController : MonoBehaviour
{
public float walkingSpeed = 7.5f;
public float runningSpeed = 11.5f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
public Camera playerCamera;
public float lookSpeed = 2.0f;
public float lookXLimit = 45.0f;
CharacterController characterController;
Vector3 moveDirection = Vector3.zero;
float rotationX = 0;
[HideInInspector]
public bool canMove = true;
void Start()
{
characterController = GetComponent<CharacterController>();
// Lock cursor
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
// We are grounded, so recalculate move direction based on axes
Vector3 forward = transform.TransformDirection(Vector3.forward);
Vector3 right = transform.TransformDirection(Vector3.right);
// Press Left Shift to run
bool isRunning = Input.GetKey(KeyCode.LeftShift);
float curSpeedX = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Vertical") : 0;
float curSpeedY = canMove ? (isRunning ? runningSpeed : walkingSpeed) * Input.GetAxis("Horizontal") : 0;
float movementDirectionY = moveDirection.y;
moveDirection = (forward * curSpeedX) + (right * curSpeedY);
if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
{
moveDirection.y = jumpSpeed;
}
else
{
moveDirection.y = movementDirectionY;
}
// Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
// when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
// as an acceleration (ms^-2)
if (!characterController.isGrounded)
{
moveDirection.y -= gravity * Time.deltaTime;
}
// Move the controller
characterController.Move(moveDirection * Time.deltaTime);
// Player and Camera rotation
if (canMove)
{
rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
}
}
}
- 将 SC_FPSController 脚本附加到"FPSPlayer"对象(您会注意到它还添加了另一个名为 Character Controller 的组件,将其中心值更改为 (0, 1, 0))
- 将主摄像头分配给 SC_FPSController 中的玩家摄像头变量
FPS 控制器现已准备就绪!