Unity用2Dキャラクターコントローラー

2D プラットフォーマー は、プレイヤーがプラットフォーム間をジャンプし、障害物を回避し、敵と戦うタイプのゲームで、すべてが 2D サイドビューの視点から観察されます。

Sharp Coder ビデオプレーヤー

Unity で 2D プラットフォーマー キャラクター コントローラーを作成するには、以下の手順に従います。

コントローラーは物理ベースであり、Rigidbody2D コンポーネントを使用します。

ステップ

  • 2D レベルでシーンを開きます (プレーヤーが落ちないように、レベル スプライトに 2D コライダーがアタッチされていることを確認してください)
  • 新しいゲームオブジェクトを作成して呼び出します "Player"
  • 別のゲームオブジェクトを作成し、"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 スクリプトには、プレイヤーを追跡する任意のカメラを指定できる Main Camera 変数を割り当てるオプションがあります。

2D キャラクター コントローラーの準備が整いました。

おすすめの記事
Unity 用プレーヤー 3D および 2D ウォール ジャンプ チュートリアル
Unity の 2D プラットフォーマー キャラクター コントローラーにダブル ジャンプ サポートを追加する
Unity用ヘリコプターコントローラー
Unityでクレーンコントロールを作る方法
Unity用カーコントローラー
キャラクター コントローラー Unity でリジッドボディをプッシュする機能を追加する方法
Unity用飛行機コントローラー