Unity 2D 角色控制器

2D Platformer 是一种玩家在平台之间跳跃、避开障碍物、与敌人战斗的游戏,所有这一切都是从 2D 侧视视角观察的。

Sharp Coder 视频播放器

要在 Unity 中制作 2D 平台游戏角色控制器,请按照以下步骤操作。

该控制器将基于物理并使用 Rigidbody2D 组件。

脚步

  • 使用 2D 关卡打开场景(确保关卡精灵附加了 2D 碰撞器,这样玩家就不会掉下来)
  • 创建一个新的 GameObject 并调用它 "Player"
  • 创建另一个 GameObject,将其命名为 "player_sprite" 并向其添加 Sprite Renderer 组件
  • 将您的精灵分配给 "player_sprite" 并将其移动到 "Player" 对象内

  • 创建 一个新脚本,将其命名为 "CharacterController2D" 并将以下代码粘贴到其中:

角色控制器2D.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 尺寸,直到它们与玩家 Sprite 匹配
  • 确保没有子碰撞器,并且 CapsuleCollider2D 是附加到该播放器的唯一碰撞器

在CharacterController2D脚本中,有一个选项可以分配主摄像机变量,该变量可以是跟随玩家的任何摄像机:

2D 角色控制器现已准备就绪!

推荐文章
Unity 玩家 3D 和 2D 墙跳跃教程
在 Unity 中向 2D 平台游戏角色控制器添加双跳支持
Unity 直升机控制器
如何在 Unity 中进行起重机控制
Unity 汽车控制器
角色控制器如何在 Unity 中添加推动刚体的功能
Unity 飞机控制器