Unity creates a movable 2D character

Create characters and scenes

We first create a character. Here I created a new capsule to be used as Player and a Square to be used as the ground.
Insert image description here
Next, add a collider and rigid body to the character, and a collider to the ground. Then we add a Z-axis constraint to the Player's rigid body to prevent it from tilting around. As shown below:
Insert image description here

At the same time, add an empty object as a sub-object to the character to emit rays to the ground and detect whether it touches the ground.
Place the Ground Check under the character's feet.

create ground

Next we need to create a new Layer to represent the ground.
Rename Square to Ground, and modify its Layer to Ground.
Insert image description here

Character control script

Then create a new CharacterController2D script to control the character. Mount this script on the player.

Check the ground

In order to implement the jumping function, we need to detect the existence of the ground. If the player is on the ground and presses the jump key, he can jump.
There are multiple ways to detect the ground, such as adding a sub-object trigger to the character and using the trigger to detect the ground. You can also emit rays to your feet, or you can perform collision detection on an area to see if there is any ground. This article adopts the last method.

We need to use the Physics2D.OverlapCircle method, which is used to detect 2D collisions. It creates a circular area at a specified location in the scene and then detects whether there are collisions with other objects in this area.

One of the overloads of this method is shown below, which is the overload we will use:

public static Collider2D OverlapCircle(Vector2 point, float radius, int layerMask)

The parameter meanings are as follows:

  • point: A two-dimensional vector representing the center position of the circle. This parameter specifies the coordinates of the center point of circular area detection. That is, with point as the center and the given radius as the radius, a circular area is created for collision detection.

  • radius: Represents the radius of the circular area. This parameter determines the size of the range for collision detection. The larger the radius, the higher the probability of detected colliding objects.

  • layerMask: Specifies the layer to be used for collision detection. Layers are a mechanism in Unity for controlling object visibility and collision interactions. Use layerMask to limit or exclude specific layers from collision detection.

Among them, point and radius are required parameters, while layerMask is optional. But we need to use it here to detect the ground separately.

For point, we use the position of the character sub-object created before. For radius, we create a separate attribute to indicate the range that it can detect. Of course, this value should be smaller. If it is too large, the detection will be inaccurate, even if it jumps. May also be detected on the ground.
The definition of raius is as follows:

private float groundCheckRadius = 0.2f;

Then we write the detection code as follows:

// 检测角色是否与地面接触
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);

Below is the complete code, copy it directly into your script, and then you can run it.

using UnityEngine;

public class CharacterController2D : MonoBehaviour
{
    
    
    public float speed = 5f;
    public float jumpForce = 5f;
    public Transform groundCheck;
    public LayerMask groundLayer;

    private Rigidbody2D rb;
    private bool isGrounded;
    private float groundCheckRadius = 0.2f;

    void Start()
    {
    
    
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
    
    
        // 检测角色是否与地面接触
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);

        // 获取水平输入
        float moveInput = Input.GetAxisRaw("Horizontal");

        // 应用水平速度
        rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);

        // 角色跳跃
        if (Input.GetButtonDown("Jump") && isGrounded)
        {
    
    
            rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
        }
    }
}

Next, drag the Player's sub-object Ground Check into the Ground Check property of the component, and then select the ground layer we set previously for the Ground Layer.
Insert image description here

operation result

The running result is as shown in the figure below. You can run and jump:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_44499065/article/details/132539951