Unity용 2D 캐릭터 컨트롤러

2D Platformer는 플레이어가 플랫폼 사이를 점프하고, 장애물을 피하고, 적과 싸우는 게임 유형으로, 이 모든 과정이 2D 측면 뷰 관점에서 관찰됩니다.

Sharp Coder 비디오 플레이어

Unity에서 2D 플랫폼 게임 캐릭터 컨트롤러를 만들려면 아래 단계를 따르세요.

컨트롤러는 물리 기반이며 Rigidbody2D 구성 요소를 사용합니다.

단계

  • 2D 레벨로 장면을 엽니다(플레이어가 넘어지지 않도록 레벨 스프라이트에 2D 충돌체가 부착되어 있는지 확인하세요)
  • 새로운 GameObject를 생성하고 호출합니다. "Player"
  • 다른 GameObject를 만들고 이름을 "player_sprite"로 지정하고 여기에 Sprite Renderer 구성 요소를 추가합니다.
  • 스프라이트를 "player_sprite"에 할당하고 "Player" 개체 내부로 이동합니다.

  • 새 스크립트를 만들고 이름을 "CharacterController2D"로 지정한 후 그 안에 아래 코드를 붙여넣습니다.

CharacterController2D.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(CapsuleCollider2D))]

public class CharacterController2D : MonoBehaviour
{
    // Move player in 2D space
    public float maxSpeed = 3.4f;
    public float jumpHeight = 6.5f;
    public float gravityScale = 1.5f;
    public Camera mainCamera;

    bool facingRight = true;
    float moveDirection = 0;
    bool isGrounded = false;
    Vector3 cameraPos;
    Rigidbody2D r2d;
    CapsuleCollider2D mainCollider;
    Transform t;

    // Use this for initialization
    void Start()
    {
        t = transform;
        r2d = GetComponent<Rigidbody2D>();
        mainCollider = GetComponent<CapsuleCollider2D>();
        r2d.freezeRotation = true;
        r2d.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
        r2d.gravityScale = gravityScale;
        facingRight = t.localScale.x > 0;

        if (mainCamera)
        {
            cameraPos = mainCamera.transform.position;
        }
    }

    // Update is called once per frame
    void Update()
    {
        // Movement controls
        if ((Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)) && (isGrounded || Mathf.Abs(r2d.velocity.x) > 0.01f))
        {
            moveDirection = Input.GetKey(KeyCode.A) ? -1 : 1;
        }
        else
        {
            if (isGrounded || r2d.velocity.magnitude < 0.01f)
            {
                moveDirection = 0;
            }
        }

        // Change facing direction
        if (moveDirection != 0)
        {
            if (moveDirection > 0 && !facingRight)
            {
                facingRight = true;
                t.localScale = new Vector3(Mathf.Abs(t.localScale.x), t.localScale.y, transform.localScale.z);
            }
            if (moveDirection < 0 && facingRight)
            {
                facingRight = false;
                t.localScale = new Vector3(-Mathf.Abs(t.localScale.x), t.localScale.y, t.localScale.z);
            }
        }

        // Jumping
        if (Input.GetKeyDown(KeyCode.W) && isGrounded)
        {
            r2d.velocity = new Vector2(r2d.velocity.x, jumpHeight);
        }

        // Camera follow
        if (mainCamera)
        {
            mainCamera.transform.position = new Vector3(t.position.x, cameraPos.y, cameraPos.z);
        }
    }

    void FixedUpdate()
    {
        Bounds colliderBounds = mainCollider.bounds;
        float colliderRadius = mainCollider.size.x * 0.4f * Mathf.Abs(transform.localScale.x);
        Vector3 groundCheckPos = colliderBounds.min + new Vector3(colliderBounds.size.x * 0.5f, colliderRadius * 0.9f, 0);
        // Check if player is grounded
        Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheckPos, colliderRadius);
        //Check if any of the overlapping colliders are not player collider, if so, set isGrounded to true
        isGrounded = false;
        if (colliders.Length > 0)
        {
            for (int i = 0; i < colliders.Length; i++)
            {
                if (colliders[i] != mainCollider)
                {
                    isGrounded = true;
                    break;
                }
            }
        }

        // Apply movement velocity
        r2d.velocity = new Vector2((moveDirection) * maxSpeed, r2d.velocity.y);

        // Simple debug
        Debug.DrawLine(groundCheckPos, groundCheckPos - new Vector3(0, colliderRadius, 0), isGrounded ? Color.green : Color.red);
        Debug.DrawLine(groundCheckPos, groundCheckPos - new Vector3(colliderRadius, 0, 0), isGrounded ? Color.green : Color.red);
    }
}
  • CharacterController2D 스크립트를 "Player" 개체에 연결합니다(Rigidbody2D 및 CapsuleCollider2D라는 다른 구성 요소도 추가되었음을 알 수 있습니다)
  • 플레이어 스프라이트와 일치할 때까지 CapsuleCollider2D 치수를 조정합니다.
  • 하위 충돌체가 없고 CapsuleCollider2D가 이 플레이어에 연결된 유일한 충돌체인지 확인하세요.

CharacterController2D 스크립트에는 플레이어를 따라갈 카메라가 될 수 있는 기본 카메라 변수를 할당하는 옵션이 있습니다.

이제 2D 캐릭터 컨트롤러가 준비되었습니다!

추천 기사
Unity용 플레이어 3D 및 2D 벽 점프 튜토리얼
Unity의 2D 플랫폼 게임 캐릭터 컨트롤러에 이중 점프 지원 추가
캐릭터 컨트롤러 Unity에서 강체를 푸시하는 기능을 추가하는 방법
Unity용 3D 웜 컨트롤러 튜토리얼
Unity의 캐릭터 컨트롤러에 움직이는 플랫폼 지원을 추가하는 방법
Unity용 하향식 플레이어 컨트롤러 튜토리얼
Unity용 비행기 컨트롤러