유니티 FPS 컨트롤러

FPS(또는 First-Person Shooter)는 1인칭 시점에서 주인공을 조종하는 게임입니다.

일반적인 컨트롤은 W, A, S, D로 걷기, 마우스 보기로 둘러보기, 스페이스바로 점프, 왼쪽 Shift로 질주하여 플레이어가 레벨에서 자유롭게 이동할 수 있습니다.

이 게시물에서는 Unity에서 카메라 회전과 플레이어 이동을 처리하는 FPS 컨트롤러를 만드는 방법을 보여 드리겠습니다.

단계

FPS 컨트롤러를 만들려면 다음 단계를 따르세요.

  • 새 게임 개체를 생성하고(GameObject -> 빈 항목 만들기) 이름을 지정합니다. "FPSPlayer"
  • 새로운 캡슐(GameObject -> 3D Object -> Capsule)을 생성하고 "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 컨트롤러

이제 FPS 컨트롤러가 준비되었습니다!

원천
📁FPSController.unitypackage53.91 KB
추천 기사
Unity의 FPS 플레이어에 크라우칭 추가하기
Unity용 플레이어 3D 및 2D 벽 점프 튜토리얼
캐릭터 컨트롤러 Unity에서 강체를 푸시하는 기능을 추가하는 방법
Unity용 리지드바디 기반 유성 플레이어 컨트롤러
Unity 모바일 터치 컨트롤을 만드는 방법
Unity의 캐릭터 컨트롤러에 움직이는 플랫폼 지원을 추가하는 방법
Unity에서 플레이어 움직임 만들기