A 2D Character Script in Godot

August 29, 2024 | View Comments

https://danielnouri.org/media/godot-rpg.webp

(Image courtesy FLUX.1 [schnell])

Foreword

Here's an article that demonstrates the awesome meta-llama/Meta-Llama-3.1-70B-Instruct model served by HuggingChat.

The prompt is more or less:

Please write a 2d character class for Godot in C# with the following features: - Is able to move in a 2d top-down world. - Has an animation player. - Has a double jump function. - Is documented calmly.

And then:

Can you now explain the code line by line, and build a narrative. Do this for a novice programmer who isn't even familiar with many control structures etc.

Introduction

This article explains a 2D character script in Godot, a popular open-source game engine. The script allows a character to move left and right, jump, and double jump. The programming language is C#.

The Script

/// <summary>
/// A 2D character class with movement, animation, and double jump functionality.
/// </summary>
public class Player : KinematicBody2D
{
    // Movement variables
    [Export]
    public float speed = 200.0f;

    [Export]
    public float jumpForce = 500.0f;

    [Export]
    public float doubleJumpForce = 300.0f;

    private bool isOnGround = false;
    private bool hasDoubleJumped = false;

    // Animation player
    private AnimationPlayer animationPlayer;

    public override void _Ready()
    {
        animationPlayer = GetNode<AnimationPlayer>("AnimationPlayer");
    }

    public override void _Process(float delta)
    {
        // Movement
        float moveX = Input.GetActionStrength("ui_right") - Input.GetActionStrength("ui_left");
        float moveY = Input.GetActionStrength("ui_down") - Input.GetActionStrength("ui_up");

        Vector2 movement = new Vector2(moveX, moveY).Normalized() * speed;

        // Apply movement
        MoveAndSlide(movement, Vector2.Up);

        // Check for ground collision
        isOnGround = IsOnFloor();

        // Update animation
        if (isOnGround)
        {
            if (movement.Length() > 0)
            {
                animationPlayer.Play("Walk");
            }
            else
            {
                animationPlayer.Play("Idle");
            }
        }
        else
        {
            animationPlayer.Play("Jump");
        }
    }

    public override void _Input(InputEvent @event)
    {
        // Jumping
        if (@event.IsActionPressed("ui_accept") && isOnGround)
        {
            Jump();
        }
        else if (@event.IsActionPressed("ui_accept") &&!isOnGround &&!hasDoubleJumped)
        {
            DoubleJump();
        }
    }

    private void Jump()
    {
        Velocity = new Vector2(Velocity.x, -jumpForce);
        hasDoubleJumped = false;
    }

    private void DoubleJump()
    {
        Velocity = new Vector2(Velocity.x, -doubleJumpForce);
        hasDoubleJumped = true;
    }
}

Explanation

This script is for a 2D character that can move left and right, jump, and double jump. It uses Godot's built-in physics engine to handle collisions and movement.

The script starts by defining a class called Player that inherits from KinematicBody2D. This class has several variables to store the character's movement speed, jump force, and double jump force.

The _Ready() method is called when the script is initialized. It gets a reference to the AnimationPlayer node and stores it in the animationPlayer variable.

The _Process() method is called every frame. It gets the input from the player, applies the movement, checks for ground collision, and updates the animation.

The _Input() method is called when the player presses a key or clicks the mouse. It checks if the player has pressed the "ui_accept" action (usually the space bar) and calls the Jump() or DoubleJump() method accordingly.

The Jump() and DoubleJump() methods make the character jump or double jump by setting the Velocity property.

Variables

The script uses several variables to store the character's state:

  • isOnGround: a boolean that indicates whether the character is on the ground
  • hasDoubleJumped: a boolean that indicates whether the character has double-jumped
  • speed: a float that stores the character's movement speed
  • jumpForce: a float that stores the character's jump force
  • doubleJumpForce: a float that stores the character's double jump force

Functions

The script uses several functions to encapsulate code that performs specific tasks:

  • Jump(): makes the character jump
  • DoubleJump(): makes the character double jump

Conclusion

This script is a basic example of a 2D character in Godot. It demonstrates how to use Godot's built-in physics engine to handle collisions and movement, and how to play different animations depending on the character's state. You can use this script as a starting point to create your own 2D games in Godot.