HomeiOS DevelopmentIntroduction to GDScript in Godot 4 Half 1

Introduction to GDScript in Godot 4 Half 1


Scripting is a elementary ability for any sport developer. You’ll be able to implement nearly any sport mechanic you’ll be able to consider by writing a number of scripts that tells the sport engine what to do. From making a personality transfer to creating enemy AI that taunts you from behind a canopy, it’s all doable by writing some code.

Observe: This tutorial assumes you’re acquainted with the fundamentals of nodes and scenes. In the event you’ve by no means used Godot, you might wish to observe alongside the Godot 4: Getting Began tutorial to search out your away across the editor.

On this tutorial, you’ll be taught the fundamentals of GDScript 2.0, the principle programming language of Godot 4. You’re going to create a easy sport impressed by Winterbells, a traditional Flash sport from 2006 by Ferry Halim. The aim of this sport is to leap larger and better by hitting the bells together with your white rabbit good friend.

White rabbit in snowfield, with white bells above it

The sport you’ll be making includes hitting power orbs with a robotic to spice up your self up as excessive as you’ll be able to.

GIF og robot jumping up and down

There’s nothing higher than making a small sport to get a really feel for a programming language! The tutorial is break up into two elements, on this first half you’ll study:

  • The basics of GDScript and the built-in script editor.
  • Creating and utilizing variables to alter and stability the gameplay.
  • Utilizing Godot’s highly effective sign system to cross values from one node to a different.
  • Polling for participant enter and utilizing it to alter the sport state.
  • Scripting leaping and gravity.

Getting Began

This tutorial makes use of the newest model of Godot 4, which you’ll obtain right here.

Obtain the tasks by clicking Obtain Supplies on the high or backside of the tutorial and extract the zip file to a location of your selecting. After extracting the zip, you’ll see two folders: starter and last. The starter undertaking is what you’ll be utilizing to construct upon.
To import the undertaking, open Godot and click on the Import button within the Undertaking Supervisor. Now both paste the starter folder path within the textual content area, or click on the Browse button to navigate to the folder.

Browse button is highlighted

Subsequent, click on the Import & Edit button to load the undertaking in Godot’s editor. Guarantee that the 2D display is lively and the sport scene is opened. If this isn’t the case, open it by double-clicking sport.tscn within the scenes folder.

Earlier than looking across the completely different scenes that I arrange, attempt to run the sport by urgent F5 in your keyboard or clicking the Run Undertaking button on the high proper. You need to see a blue robotic standing on the backside of the display whereas some music performs within the background.

game.tscn is highlighted

If that’s working as anticipated, it’s time to offer a fast tour across the starter undertaking.

Undertaking Tour

I’ve ready some primary scenes and property so you’ll be able to focus totally on scripting. To start out off, check out the FileSystem dock and the folders and information inside:

  • music: A single audio file that’s used for the background music.
  • scenes: All scenes used all through the undertaking. Extra on these under.
  • sounds: A glass-shattering sound impact.
  • sprites: This incorporates the background graphics and the sprite sheets for the robotic and jumper orbs.
  • credit.txt: A listing of sources and attributions for the included property.

Subsequent up is a quick overview of the scenes.

Recreation Scene

The primary and most vital one is sport. This the principle scene and it incorporates the next nodes:

  • A Camera2D with a repeating background Sprite2D as a toddler
  • A floor Sprite2D node
  • An occasion of the player_avatar scene named PlayerAvatar
  • An AudioStreamPlayer that mechanically performs and loops a music observe
  • An occasion of the ui scene named UI

List of nodes, top one reads Game

Observe: In the event you’re unsure what a particular node does, you’ll be able to right-click the node and choose Open Documentation within the context menu. This opens the documentation for that node class within the Script display.

On the finish of this tutorial, this would be the scene the place all of the motion occurs because the avatar will transfer about and hit power orbs referred to as “jumpers” to launch itself upwards. Talking of jumpers, double-click the jumper.tscn scene file to have a look what’s inside.

Jumper Scene

On this scene, the basis node Jumper is an AnimatedSprite2D which holds its animations. The Area2D node and its CollisionShape2D are used to detect collisions with the participant avatar. Lastly, ShatterSound is an AudioStreamPlayer2D that references the glass shatter sound impact discovered within the sounds folder.

List of nodes, top one reads Jumper

Now open the player_avatar scene and take a peek at its nodes.

Participant Avatar Scene

At its root is a Node2D node which is used to group its kids collectively: an AnimatedSprite2D with a number of animations and an Area2D used for detecting collisions. Easy however efficient!

List of nodes, top one reads PlayerAvatar

The ultimate scene to try is the UI scene, which yow will discover in ui.tscn.

UI Scene

The UI scene incorporates the person interface for the sport, which is a CanvasLayer that has two textual content labels to maintain observe of the peak and rating. The MarginContainer and HBoxContainer nodes align these labels to the underside of the display with some margin from the borders of the display.

List of nodes, top one reads UI

That concludes the undertaking tour. Don’t fear in case you’re unsure what the scenes are speculated to just do but, you’ll get acquainted with the smaller particulars whereas including logic by way of scripts and playtesting. With the chook’s eye view out of the best way, it’s time to begin your GDScript adventures!

Why GDScript?

GDScript is a high-level, object-oriented programming language that was constructed particularly to be used with the Godot sport engine. Whereas different languages like C# and C++ will also be used with Godot, GDScript is commonly the language of selection because of the wealth of examples, questions, and tutorials out there on-line. It’s additionally the first-class citizen in Godot because it’s absolutely supported by the built-in script editor.

In the event you’re acquainted with Python, you then’ll discover GDScript’s syntax to be intuitive and simple to be taught. Even with minimal information of different programming languages, you’ll be comfy with the language with a couple of days of follow.

On this tutorial, all scripting will likely be completed utilizing Godot’s built-in script editor, so that you gained’t want the rest to get began. In the event you favor to write down your code in a unique window or IDE, you should utilize an exterior editor like Visible Studio Code, Vim or Elegant Textual content. Personally, I like to recommend utilizing Visible Studio Code with the godot-vscode-plugin, regardless that some capabilities like debugging should not but suitable with Godot 4.

As a last advice, listed below are two editor settings for the built-in script editor you would possibly wish to change by way of Editor ▸ Editor Settings within the high menu:

  • Disable Textual content Editor ▸ Habits ▸ Clean Scrolling. It is a private desire, however I discover clean scrolling slows down the velocity to navigate a script by scrolling.
  • Allow Textual content Editor ▸ Completion ▸ Add Sort Hints. This provides static typing to variables and capabilities generated by Godot, which improves efficiency, autocompletion and reduces the chance of bugs. I’ll clarify why that is the case later within the tutorial.

Scripting Fundamentals

Let’s put the speculation and background data apart for now and deal with what you got here right here to do: write scripts!

Creating New Scripts

To start out off, create a brand new folder on the root of the undertaking’s filesystem by right-clicking res:// and choosing New ▸ Folder.

New and Folder are highlighted

This folder will maintain all of the scripts, so title it scripts. The primary script you’re going to create will likely be for the participant avatar, so open the player_avatar scene. Now choose the basis PlayerAvatar node and press the connect script button that appears like a scroll with a inexperienced plus signal.

White scroll with green plus icon is highlighted

This opens the Connect Node Script window, which you should utilize to set the preliminary settings for the script.

Window with several fields, path is highlighted

Right here’s a rundown of those settings:

  • Language: Godot helps different languages apart from GDScript, which you’ll select right here. The default construct of Godot solely comes with GDScript, whereas the .NET construct additionally has C# included.
  • Inherits: The Node class to inherit the script from. This offers your script entry to variables and capabilities distinctive to that node sort.
  • Class Title: The category title of the script. This solely applies to completely different languages than GDScript. For C# this might be PlayerAvatar for instance.
  • Template: What script template to use. This modifications how the brand new script will likely be structured, with or with out feedback for instance. Godot comes with a Default and an Empty template out of the field. You too can create your individual script templates.
  • Constructed-in Script: By default, Godot saves scripts as information. When that is checked, the script is constructed into the scene itself. This may be helpful in uncommon instances, however having exterior scripts is extra intuitive and higher for supply management.
  • Path: Undertaking path the place Godot will create the brand new script.

Discover that the trail factors to the scenes folder by default. Be sure that to exchange “scenes” with “scripts” within the path, both by hand or by clicking the folder icon and navigating to the scripts folder. The default filename “player_avatar.gd” is ok as Godot makes use of snake_case for its information and folders. With the right path set, click on the Create button to create the script.

Path and create button

This can mechanically open the script editor with the brand new script opened. Press CTRL/CMD + S to save lots of the scene and the script after which have a look across the completely different elements of the editor.

Script editor overview

Under is a abstract of the completely different sections:

  1. The toolbar positioned on the high of the display incorporates a menu on the left with typical instructions present in textual content editors plus some helpful scripting choices like altering the syntax highlighting. On the fitting facet are two buttons; On-line Docs which opens Godot’s on-line documentation in your default net browser, and Search Assist which opens a search window that lets you search and discover information concerning the built-in courses.
  2. Opened scripts are displayed on the high, whereas the underside listing reveals the capabilities of the script you’re enhancing.
  3. The textual content editor shows the content material of the script, and is the principle workspace you’ll use all through this tutorial. On the high proper is a minimap, which makes it straightforward to shortly navigate bigger scripts.
  4. The panel on the backside has an arrow button to cover the 2 lists on the left, and reveals any warnings and errors on the proper, together with the road quantity and column the caret is positioned on.

Now you’re a bit extra acquainted with the interface, it’s time to have a look at the script itself.

Script Anatomy

Godot’s default script template makes for an awesome start line to construct upon additional. It even incorporates some helpful feedback! I’ll bridge the hole to make it extra apparent what the unexplained elements do.
The primary line reads extends Node2D, which implies this script inherits from the Node2D class. The extends key phrase permits your script to make use of the variables and capabilities from the inherited class.

Under which are two of essentially the most used capabilities in Godot: _ready and _process. Because the feedback counsel, _ready is known as as soon as firstly of the node’s lifespan, whereas _process is known as each body. These are overrides for the digital capabilities of the identical title within the Node class, the category all different node-based courses inherit from. You’ll be able to see which capabilities override their base class by little blue arrow in entrance of the road quantity.

Blue arrows pointing at code

Each capabilities begin with an underscore to mark them as non-public, which means you shouldn’t name these capabilities from one other script. Godot doesn’t implement this in any approach although, it’s a conference to maintain your code clear.
The cross key phrase in each capabilities is a placeholder, it doesn’t do something apart from ensuring there’s one thing indented contained in the perform so Godot doesn’t throw errors. Strive eradicating the entire cross line within the _ready perform to see for your self.

Function with pass keyword removed

This can present an error on the backside saying: “Anticipated indented block after perform declaration”. GDScript makes use of indentation with tabs (or areas) to specify what code belongs to what perform or assertion. Now change the _ready perform as follows:

func _ready() -> void:
    print("Participant avatar has loaded!")

The print perform prints arguments of any sort to the output console. Save the script and run the sport by urgent F5 to see it in motion.
If every thing went effectively, you need to now see the textual content being displayed on the backside. In the event you don’t see the console, click on the Output button to toggle it on.

Console

With the basics lined, you’re now able to faucet into the ability of GDScript!

Variables

The participant avatar wants to maneuver left and proper in direction of the place of the cursor. To do that, you’ll want preserve observe of the avatar’s present velocity, its motion velocity and the mouse place. You’ll be able to retailer these values as variables in your script.
You’ll be able to outline variables in Godot utilizing the var key phrase. To start out with, outline a brand new variable named velocity that may be accessed all through the script by including this line under extends Node2D:

var velocity : Vector2 = Vector2.ZERO

There are some things occurring right here:

  • var velocity defines a brand new variable and names it velocity. This by itself is sufficient to create a brand new variable in case you don’t care concerning the sort or default worth.
  • : Vector2 units the sort of variable, on this case a Vector2, which has a x and y coordinate to carry the horizontal and vertical velocity respectively.
  • = Vector2.ZERO offers the variable a default worth. Vector.ZERO is a continuing with a worth of 0 for each x and y.

Offering a kind for variables is non-compulsory in Godot, this referred to as dynamic typing. Setting the kind whereas defining new variables such as you simply did is known as static typing. You need to favor static typing over dynamic typing for a number of causes:

  • It makes Godot’s compiler perceive what you’re tying to do higher, which ends up in higher autocompletion within the script editor.
  • The code will likely be extra readable because it’s clear what worth a variable can maintain. This in flip makes your code much less error-prone.
  • You get an enormous efficiency enhance free of charge, as statically typed code runs between 25 and one hundred pc sooner than its dynamic counterpart.

All variables all through this tutorial will use static typing to make it simpler to observe alongside and be taught the different sorts.

Subsequent on the listing is the motion velocity, which is the velocity at which the avatar will transfer horizontally in pixels per second. Not like the speed, you need to have the ability to tweak its worth by way of the inspector. Add the next line under extends Node2D so as to add a brand new move_speed variable:

@export var move_speed : float = 600.0

By including the @export annotation earlier than the variable declaration, it exposes the variable to the editor. That is extraordinarily helpful for shortly altering values to enhance the stability or really feel of your sport. The move_speed variable is a float, which is brief for floating-point quantity. It might retailer numerical values with decimal digits and is commonly used for positional calculations.

Save the script player_avatar script, be sure you’ve acquired the PlayerAvatar node chosen within the Scene dock and check out the Inspector on the fitting. You need to now see a brand new property named Transfer Pace with the a worth of 600.

Move speed 600

I discovered 600 pixels per second to be a wise velocity, however you’ll be able to change this worth as soon as the avatar can transfer to make the sport easier or troublesome. Subsequent on the listing is getting the participant to maneuver the mouse cursor.
For this to work, you’ll must get the place of the cursor, examine whether or not it’s left or proper from the avatar after which alter the speed accordingly each body. To get the place of the mouse cursor, substitute the cross key phrase within the _process perform with this:

var mouse_pos : Vector2 = get_global_mouse_position()

This grabs the place of the cursor by way of the built-in get_global_mouse_position() perform, which returns a Vector2. To check if that is working, you’ll be able to add the next print name under the road you simply added:

print(mouse_pos)

This can print the cursor place each body. Go forward and provides it a go by urgent F5 in your keyboard to run the scene. Transfer your mouse round a bit and also you’ll see the positions showing within the console.

647, 275 in console

Now you recognize that’s working, take away the print line you added for testing functions and substitute it with the next to make the avatar transfer to the cursor:

Observe: In the event you get an error saying “Combined use of tabs and areas for indentation” whereas copying any of the code snippets to your scripts, press CTRL/CMD + I in your keyboard whereas within the script editor. This can mechanically repair any incorrect indentation. The explanation you would possibly get this error when copying snippets from an internet browser is as a result of they have a tendency to transform tabs to areas, whereas Godot expects tabs.

    var x_distance_to_cursor = mouse_pos.x - global_position.x # 1
    var cursor_right : bool = x_distance_to_cursor > 0 # 2

    if cursor_right: # 3
        velocity.x = move_speed
    else:
        velocity.x = -move_speed

    global_position += velocity * delta # 4
  1. Calculate the space to the cursor by subtracting the avatar’s X place from the cursor’s X place. For instance, if the avatar’s place is (X:10, Y:0) and the cursor’s place is (X:50, Y:0), the space can be 40 pixels. Retailer this worth in a brand new variable named x_distance_to_cursor.
  2. Test if the cursor is correct or left from the avatar by getting the space calculated above and seeing if it’s a optimistic or destructive worth. A optimistic worth means the cursor is to the fitting. Retailer this in a boolean variable named cursor_right. A boolean has two doable values: true or false.
  3. That is an if-statement that modifications the X-value of the velocity to the motion velocity if the cursor is to the fitting, or to the destructive motion velocity if the cursor is to the left. If-statements in GDScript observe the identical guidelines as capabilities, so something that applies to the assertion ought to be indented with a tab and the statements finish with a colon.
  4. The global_position variable is a part of the Node2D class and shops the node’s place as a Vector2. The code applies the velocity to the avatar’s world place and multiplies it with delta to make it framerate-independent.

That was lots to soak up directly! Your efforts are rewarded although, as you’ll see when working the sport by urgent F5.

GIF of robot moving left and right

The avatar now easily follows your cursor! You might need observed a bit of quirk although: whenever you transfer the cursor exterior of the borders of the window, the avatar follows and disappears off-screen. To repair this, you will get the rectangle that makes up the viewport, add a border to the edges and restrict the avatar’s horizontal motion inside.

Window with red borders left and right

The illustration above reveals the idea of a digital border that the avatar can’t cross with a crimson colour. To implement this in code, you want the measurement of the viewport, the border width and the avatar’s place. To get the viewport’s measurement, add this line to the _process perform, under mouse_pos:

var viewport_size : Vector2 = get_viewport_rect().measurement

This line will get the viewport’s rectangle, which is the place and measurement of the sport window, and extracts simply the measurement from it. This worth then will get saved in viewport_size.
For the border, you’re going so as to add one other exported variable, so you’ll be able to tweak its worth within the Inspector. To try this, add the next to the highest of the script, proper under the move_speed variable declaration:

@export var viewport_border : float = 80.0

That is the width of the border in pixels. To truly restrict the avatar’s motion, alter the velocity-changing if-statement in _process as follows:

    velocity.x = 0 # 1

    if cursor_right:
        if global_position.x < viewport_size.x - viewport_border: # 2
            velocity.x = move_speed
    else:
        if global_position.x > viewport_border: # 3
            velocity.x = -move_speed

Right here’s what this does:

  1. Reset the horizontal velocity so the avatar doesn’t transfer if there’s no horizontal velocity utilized additional down.
  2. If the avatar needs to maneuver to the fitting, solely permit it if its place hasn’t handed the border on the fitting. The border calculation takes the horizontal measurement of the window and subtracts the scale of the border from it.
  3. This does the identical as above, however for transferring to the left. As an alternative of taking the scale of the viewport into consideration, you merely use the border measurement because the leftmost viewport place is 0.

With this added, run the sport once more and transfer your cursor exterior of the window. The avatar will now wait patiently at one of many borders.

GIF of robot moving left and right

With the horizontal motion completed, you’re now able to discover Godot’s sign system.

Indicators

A sign in Godot is a message emitted by a node when a sure occasion happens. Nodes can subscribe these alerts to do actions of their very own. Some built-in examples if alerts embody:

  • The urgent of a button
  • A node coming into the viewport
  • The collision of two areas
  • A sound impact that completed taking part in

This a strong system that lets you preserve your code versatile and loosely coupled, because the node emitting the sign doesn’t care about its subscribers.

To start out off, open the jumper scene within the scenes folder and add a brand new script to the Jumper node named jumper.gd. Like with the player_avatar script, make certain to position it within the scripts folder.

Jumper and Path are highlighted

After creating the script, it ought to be mechanically opened within the script editor. Take away each the _ready and _process capabilities, as you gained’t want them. You ought to be left with simply this line:

extends AnimatedSprite2D

In distinction to the participant avatar’s Node2D, the basis node sort for the jumper is an AnimatedSprite2D, which inherits from Node2D and provides assist for animations.
You’ll be utilizing a sign to detect when the avatar enters a jumper’s Area2D node. Indicators may be linked to a script both by way of the editor or by way of code, on this case by way of the editor makes essentially the most sense. Choose the Area2D node within the Scene dock and open the Node tab subsequent to the Inspector tab.

Node tab highlighted

You’ll now see an inventory of alerts the chosen node helps.

Signals list

Within the case of Area2D, this listing is huge and filled with helpful sign to hook up with. To detect when one other Area2D enters this one, you’ll want the area_entered sign, so double click on it to begin connecting it. This can present a dialog window with some choices for the connection.

Signal connect window

By default, it can choose the basis node, Jumper because the node to hook up with. That is what you need, so there’s nothing to alter there.
Under that’s the Receiver Methodology, that is the title of the perform that will likely be referred to as when the area_entered sign is emitted. The default worth, _on_area_2d_area_entered works fantastic on this case. Now click on the Join button to attach the sign, this can add the brand new perform to the jumper script.

Green symbol before function code

Any longer, at any time when one other Area2D enters the Jumper’s Area2D, this perform will likely be referred to as. You’ll be able to inform the perform is linked to a sign by the inexperienced “exit” image to the left of it. Clicking that reveals what alerts will name this perform.

Area2D, area_entered, Jumper

To check if this really works, substitute the cross key phrase with the road under:

print("Received hit!")

By now I’m positive you recognize precisely what this does: printing textual content to the console, a programmer’s greatest good friend.
Save the script and open the sport scene in 2D mode. Now drag a couple of situations of the jumper scene from the FileSystem dock onto the viewport, subsequent to the participant avatar.

Dragging jumper scene

What you simply did there’s referred to as instantiating scenes, which is utilizing a scene as a blueprint and creating situations of it in one other scene. This highly effective system lets you create a scene as soon as, and use it wherever you want.
With the jumpers added, press F5 to play the undertaking. Transfer the avatar in opposition to the jumpers and you need to see messages popping up within the console as anticipated.

Got Hit in console

Now to make issues extra fascinating, the next ought to occur when a jumper will get hit:

  • Play a shatter sound
  • Play a shatter animation
  • Destroy the jumper on the finish of the animation

How do you do all of this? By scripting after all! Open the jumper scene once more and swap to the script editor. To play a sound impact, you want a reference to an AudioStreamPlayer node first. In the event you bear in mind, jumper occurs to have one named ShatterSound.

ShatterSound

There are two methods so as to add a reference to a node in your scripts when working within the built-in script editor: the boring handbook technique or the superior speedy technique. I’ll begin off with the primary one, which is including the next line under extends AnimatedSprite2D:

@onready var shatter_sound : AudioStreamPlayer2D = $"ShatterSound"

I like to recommend typing this one out your self in case you haven’t been doing so already, to see how the auto completion helps you by itemizing all nodes within the scene when you get to the final half.

GIF of autocompletion

Right here’s a breakdown of this variable declaration:

  • @onready is an annotation like @export. This makes it so the variable will get assigned when the node enters the node tree for the primary time. This would possibly ring a bell, as that’s the identical time because the _ready perform is known as you’ve seen earlier than. In essence, @onready lets you write one-liners to create and assign a node to a variable.
  • var shatter_sound declares a brand new variable.
  • : AudioStreamPlayer2D specifies the kind of the variable as a AudioStreamPlayer2D.
  • = $"ShatterSound" will get a reference to the node named ShatterSound. The greenback signal ($) is shorthand for the get_node() perform.

Now you recognize what this line does, it’s time to be taught concerning the extra thrilling approach so as to add a reference to a node.
Take away the road you simply added and begin dragging the ShatterSound node from the Scene dock into the script editor. Maintain CTRL/CMD earlier than releasing your mouse button to finish the drop. This can add a node reference mechanically, how cool is that?

Drag node to script editor with instructions to hold CTRL or CMD before releasing

You’re now one of many few those who find out about this arcane information, use this energy effectively!
With the reference to the AudioStreamPlayer arrange, now you can make it play its sound impact at any time when the avatar hits the jumper by changing the print name with this:

shatter_sound.play()

This calls the play perform on the AudioStreamPlayer, which is able to make a pleasant glass shattering sound. Save the script and run the undertaking to offer it a strive. At any time when the avatar passes over a jumper, you need to hear the sound impact play.
If that’s working as anticipated, you’ll be able to transfer on to taking part in the shatter animation, which is so simple as including this line under the road you simply added:

animation = "destroy"

As a result of Jumper is an AnimatedSprite2D node, it has a property referred to as animation, which units the present animation by its title. If you choose the Jumper node and check out the underside of the editor, you’ll see an inventory of accessible animations. The default animation is aptly referred to as “default”, whereas the animation you’re setting right here is known as “destroy”.

default and destroy animations

As soon as once more, it’s time to check if that is working as anticipated, so play the undertaking and check out transferring into the jumpers once more. The jumpers ought to now shatter when hit!

GIF of robot hitting orbs, which shatter

On to the precise self-destructing, which ought to occur after the animation finishes taking part in. There’s approach of realizing when the animation ends in the intervening time, and whilst you may use some form of timer, a way more elegant approach is by utilizing a sign. AnimationSprite2D has an animation_finished sign you’ll be able to connect with, however connecting it by way of the editor now would end in it being emitted consistently because the default animation is taking part in on a loop.

The answer is to attach the sign by way of code after beginning the destroy animation, as that ensures good timing and the perform is barely being referred to as as soon as. To start out off, create a brand new perform that you simply wish to be referred to as by the sign to the tip of the script:

func _destroy_animation_finished() -> void:
    queue_free()

As this perform isn’t supposed for use exterior of the script, it begins with an underscore. It does one factor: name the queue_free() technique, which queues up the Jumper node for elimination from the node tree, successfully destroying it.
To attach the animation_finished sign to the _destroy_animation_finished perform, add the next line under animation = "destroy" within the _on_area_2d_area_entered perform:

animation_finished.join(_destroy_animation_finished)

This connects animation_finished to _destroy_animation_finished, similar to how you probably did it earlier than by way of the editor. The good thing about connecting alerts by way of code is that it makes it straightforward to “rewire” alerts simply by enhancing a couple of variables and you may join and disconnect them everytime you please. All of this performs into the modular nature of working with Godot and its nodes.
Play the undertaking as soon as once more to check if the jumpers disappear after their animation finishes.
There’s a small bug although which may not be apparent right away: in case you hit a jumper, transfer away and hit it once more earlier than the animation finishes, the sound impact will play a second time and also you’ll get an error. Right here’s what it says:

<code>jumper.gd:9 @ _on_area_2d_area_entered(): Sign 'animation_finished' is already linked to given callable 'AnimatedSprite2D(jumper.gd)::_destroy_animation_finished' in that object.</code>

This error is thrown as a result of there was already a connection made on the animation_finished sign. In different phrases, the _on_area_2d_area_entered perform acquired referred to as twice on the identical jumper, which is undesirable. To repair this, you’ll be able to set a flag on the jumper that states whether or not the jumper is lively or not. When inactive, it shouldn’t react to any collisions.
To implement this, add the next variable under extends AnimatedSprite2D:

var lively : bool = true

This boolean will act because the flag and it begins as true, which means jumper will likely be lively out of the gate. Subsequent, change the code contained in the _on_area_2d_area_entered perform as follows to make use of the flag:

if lively: # 1
    lively = false # 2
    shatter_sound.play()
    animation = "destroy"
    animation_finished.join(_destroy_animation_finished)

Right here’s what this does:

  1. An if-statement that checks if the jumper is lively earlier than doing the rest.
  2. Set the lively flag to false. This can forestall the code being ran greater than as soon as.

Make sure to save the script when you’re completed. With this security examine added, the script is bug-free and also you’re able to make the avatar soar.

Soar Utilizing Participant Enter

The aim of the sport will likely be flying from jumper to jumper, so that you want a approach of propelling the avatar upwards. The primary soar will likely be carried out with a mouse click on, which implies you want a way of studying the participant’s enter and act upon it.

Whilst you can laborious code mouse button polling, Godot has a helpful enter system that makes use of enter actions to deal with participant enter. Take a personality transferring ahead for instance, with out enter actions you’d have one thing like this:

if Enter.is_physical_key_pressed(KEY_W) || Enter.is_physical_key_pressed(KEY_UP) || Enter.get_joy_axis(0, JOY_AXIS_LEFT_Y) < 0:
    move_forward()

With enter actions, you’ll be able to assign the W key, arrow up key and joystick up to an motion and examine that:

if Enter.is_action_pressed("move_forward"):
    move_forward()

That’s an entire lot nicer, isn’t it? This lets you reassign keys and buttons tied to an motion from the editor and even throughout gameplay. You too can assign a number of inputs to the identical motion.
So as to add an motion your self, first choose Undertaking ▸ Undertaking Settings… within the high menu to open the undertaking settings.

Project settings

Now open the Enter Map by clicking the corresponding tab on the high.

Input map

This the place you’ll be able to outline new actions. Add a soar motion by clicking the Add New Motion area, typing “soar” adopted by clicking the Add button to its proper.

GIF of adding new action

With the soar motion added, you’ll be able to add enter occasions to it by clicking the plus button subsequent to its title. This opens the Occasion Configuration window. In right here, choose Mouse Buttons ▸ Left Mouse Button and click on the OK button on the backside to substantiate.

Left mouse button, OK

Again within the Enter Map, now you can see the soar motion is tied to the left mouse button. Candy!

Left mouse button, all devices

Go forward and shut the Undertaking Settings window. Now open the player_avatar script once more because it wants some additions to make the avatar soar.
To start out with, add a brand new variable for the soar velocity to the highest of the script, under viewport_border:

@export var jump_speed : float = 2500.0

That is the vertical velocity of the avatar when leaping, at any time when it jumps from the bottom or when it hits a jumper, that is the quantity of pixels per second it can journey at. To make use of it, add the next perform under the _process perform:

func _jump() -> void:
    velocity.y = -jump_speed

This _jump perform will change the Y velocity of the avatar to the worth of the soar velocity you simply added, however destructive. The worth needs to be negated as optimistic Y means down in Godot, whereas destructive Y means up.
To name _jump, add this perform above the perform you simply added:

func _process_input() -> void:
    if Enter.is_action_just_pressed("soar"):
        _jump()

This perform calls upon the Enter class to examine whether or not the soar motion was simply pressed after which calls the _jump() perform if that’s the case. The is_action_just_pressed technique checks for a single press, not a steady maintain, not like is_action_pressed. To complete the perform chain, add this line on the finish of the _process perform:

_process_input()

This can name the _process_input perform each body, which in flip checks for any inputs. Whilst you may have put every thing in _process, that makes it tougher to trace down the items of code and alter them in a while. Writing clear code is a ability in itself. :]
Time for an additional check drive, press F5 to play the undertaking and attempt to make the participant soar.

Robot jumping up and disappearing

I’d say that could be a profitable soar. It’s extra like a rocket launch in the intervening time, however that’s fixable!
The explanation why the avatar leaves the display and by no means returns is as a result of there’s no gravity utilized to it. What goes up should come down in spite of everything. Add a brand new variable under jump_speed named gravity:

@export var gravity : float = 4000.0

It is a downward drive that will likely be utilized to the avatar. To use it each body, add this line to _process, proper under velocity.x = 0:

velocity.y += delta * gravity

This can push the avatar down repeatedly, simulating gravity. Run the undertaking once more to see if this improves the leaping. You’ll discover the avatar falls down right away and retains falling, except you click on at times to bounce it again up.

Robot constantly jumping and falling

This concludes the primary a part of the tutorial, what a cliffhanger! Or is it cliff-faller on this case? :]
Don’t fear, within the second a part of this tutorial you’ll assist the poor avatar out so it doesn’t have to leap on a regular basis to forestall falling the limitless abyss.

The place to Go From Right here?

Thanks for studying this primary a part of the tutorial! You’ll be able to obtain the undertaking information utilizing the hyperlink on the high and backside of this web page.
Within the second a part of this tutorial, you’ll discover ways to use a finite state machine to neatly handle the avatar’s state, instantiate scenes utilizing code, make the digicam observe the avatar and far more! On the finish, you’ll have a small sport to construct upon additional.

We hope you loved this primary a part of the tutorial. Depart a remark under or be a part of the discussion board dialogue to share your ideas and ask any questions you might need!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments