Back to blog

Saturday, September 21, 2024

Build a 2D Platformer in Godot


FacebookTwitterInstagramEmailWhatsAppMessages

Full Guide to Building a 2D Platformer in Godot

This comprehensive guide will teach you how to create your first 2D platformer game in Godot. The game will involve a character jumping on platforms, collecting coins, and moving across different levels. By the end, you’ll have a simple but fully functional game.


Table of Contents


Setting Up the Project

1. Installing Godot

Before starting, make sure you have Godot Engine installed. You can download it from the official Godot website.

  1. Open Godot and create a New Project.
  2. Name your project PlatformerGame and choose a location to save it.
  3. Click Create & Edit.
Setting up Godot project

2. Setting up the Main Scene

In Godot, everything starts with a scene. A scene can be anything: a character, a platform, a UI, or an entire game level.

  1. Create a new 2D Scene by clicking the + button at the top of the scene tree.
  2. Rename the root node to MainScene.
  3. Save the scene as MainScene.tscn.

This will serve as the foundation of our game.


Creating a Player Character

1. Adding the Player Node

  1. Add a KinematicBody2D node to represent the player. This node allows us to handle custom physics and movement.
  2. Add a Sprite node as a child of KinematicBody2D. This will serve as the visual representation of our player.
  3. Add a CollisionShape2D as a child of the player. Set the shape to RectangleShape2D to define the player’s collision area.

2. Creating Player Movement

To make the player move and jump, we need to attach a script to the player.

  1. Select the KinematicBody2D node.
  2. Click on the Script icon (or right-click and select Attach Script).
  3. Write the following code for movement and jumping:
extends KinematicBody2D

var velocity = Vector2()
var speed = 200
var gravity = 600
var jump_force = -400

func _physics_process(delta):
    velocity.y += gravity * delta

    if Input.is_action_pressed("ui_right"):
        velocity.x = speed
    elif Input.is_action_pressed("ui_left"):
        velocity.x = -speed
    else:
        velocity.x = 0

    if is_on_floor() and Input.is_action_pressed("ui_up"):
        velocity.y = jump_force

    velocity = move_and_slide(velocity, Vector2.UP)

This script handles horizontal movement (left and right), gravity, and jumping.

3. Setting Up the Input Map

We need to define controls for movement and jumping.

  1. Go to Project > Project Settings.
  2. Under the Input Map tab, add new actions:
    • ui_right for moving right (Assign it to the right arrow key or D).
    • ui_left for moving left (Assign it to the left arrow key or A).
    • ui_up for jumping (Assign it to the up arrow key or Space).
Godot Input Map Setup

Adding Platforms

Platforms in a 2D game are static objects that the player can walk and jump on.

1. Creating the Platform Node

  1. In the scene, add a StaticBody2D node. This is a static object that will not move but can interact with other bodies.
  2. Add a Sprite to give the platform a visual appearance (use any platform image or texture).
  3. Add a CollisionShape2D and set it to RectangleShape2D.

2. Reusing Platforms

  1. Save the platform node as a new scene (Platform.tscn) so you can reuse it multiple times.
  2. In your main scene (MainScene.tscn), instance the platform scene as many times as needed to build the level.
Platform Scene in Godot

Coin Collection and Scoring

1. Adding a Coin Node

Coins are collectibles that increase the player’s score.

  1. Create a new Area2D node for the coin.
  2. Add a Sprite for the coin’s appearance and a CollisionShape2D.
  3. Attach a script to the coin that allows it to be collected:
extends Area2D

signal coin_collected

func _on_body_entered(body):
    if body.name == "Player":
        emit_signal("coin_collected")
        queue_free()  # Remove coin after collection

2. Displaying the Score

  1. Add a Label node to display the score in the game.
  2. In your main scene script, connect the coin’s signal to the function that updates the score:
var score = 0

func _on_coin_collected():
    score += 1
    $ScoreLabel.text = "Score: " + str(score)

Level Progression and Game Over

1. Handling Level Progression

To move from one level to the next, you can add an Area2D at the end of a level that will load the next scene when entered:

func _on_LevelEnd_body_entered(body):
    if body.name == "Player":
        get_tree().change_scene("res://Level2.tscn")

2. Restarting the Game on Fall

If the player falls off the screen, we can reset the scene:

if position.y > 600:
    get_tree().reload_current_scene()

Background Music and Effects

1. Adding Background Music

To enhance the game experience, we can add background music using an AudioStreamPlayer.

  1. Add an AudioStreamPlayer node to the scene.
  2. Load your desired music file into the Stream property and enable Autoplay.

2. Adding Sound Effects

You can add sound effects for jumping, collecting coins, etc., using additional AudioStreamPlayer nodes and scripts.


Final Touches

1. Particle Effects

To make the game visually appealing, you can add Particles2D for effects like jumping dust or coin sparkle.

2. Polishing the Game

Add animations for walking, jumping, and idle using an AnimatedSprite node. You can create multiple animation frames for smooth transitions between states.

3. Packaging the Game

Once you’ve completed your game, go to Project > Export and export the game for your desired platform (PC, mobile, etc.).


Screenshot of the final game

This concludes our full tutorial on creating a 2D platformer game in Godot! You can expand this game by adding more levels, power-ups, and enemies. Keep experimenting, and most importantly, have fun!


### Key Features Included:
- Full breakdown of steps with Godot engine setup
- Player movement, jumping, and gravity mechanics
- Coin collection, scoring system, and level transitions
- Background music, sound effects, and particle effects for polish
- Placeholder images (to be replaced by actual screenshots)