Scripting is a elementary talent for any sport developer. You’ll be able to implement nearly any sport mechanic you may 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 potential by writing some code.
On this tutorial, you’ll study the fundamentals of GDScript 2.0, the primary programming language of Godot 4. You’re going to create a easy sport impressed by Winterbells, a basic 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.
The sport you’ll be making entails hitting vitality orbs with a robotic to spice up your self up as excessive as you may.
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 find out about:
- The basics of GDScript and the built-in script editor.
- Creating and utilizing variables to vary and steadiness the gameplay.
- Utilizing Godot’s highly effective sign system to go values from one node to a different.
- Polling for participant enter and utilizing it to vary the sport state.
- Scripting leaping and gravity.
Getting Began
This tutorial makes use of the latest 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 remaining. The starter venture is what you’ll be utilizing to construct upon.
To import the venture, open Godot and click on the Import button within the Mission Supervisor. Now both paste the starter folder path within the textual content subject, or click on the Browse button to navigate to the folder.
Subsequent, click on the Import & Edit button to load the venture in Godot’s editor. Make it possible for the 2D display is energetic 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 having a look across the completely different scenes that I arrange, attempt to run the sport by urgent F5 in your keyboard or clicking the Run Mission 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.
If that’s working as anticipated, it’s time to provide a fast tour across the starter venture.
Mission Tour
I’ve ready some primary scenes and property so you may 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 venture. Extra on these under.
- sounds: A glass-shattering sound impact.
- sprites: This accommodates 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 short overview of the scenes.
Sport Scene
The primary and most vital one is sport. This the primary scene and it accommodates the next nodes:
- A Camera2D with a repeating background Sprite2D as a baby
- A floor Sprite2D node
- An occasion of the player_avatar scene named PlayerAvatar
- An AudioStreamPlayer that robotically performs and loops a music observe
- An occasion of the ui scene named UI
Notice: If you happen to’re undecided what a particular node does, you may 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 vitality 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 foundation 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.
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 youngsters collectively: an AnimatedSprite2D with a number of animations and an Area2D used for detecting collisions. Easy however efficient!
The ultimate scene to check out is the UI scene, which you will discover in ui.tscn.
UI Scene
The UI scene accommodates 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.
That concludes the venture tour. Don’t fear should you’re undecided what the scenes are alleged to do exactly but, you’ll get conversant in the smaller particulars whereas including logic by way of scripts and playtesting. With the chook’s eye view out of the way in which, 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 usually the language of selection because of the wealth of examples, questions, and tutorials obtainable on-line. It’s additionally the first-class citizen in Godot because it’s totally supported by the built-in script editor.
If you happen to’re conversant in Python, you then’ll discover GDScript’s syntax to be intuitive and simple to study. Even with minimal information of different programming languages, you’ll be comfy with the language with a number of days of follow.
On this tutorial, all scripting will likely be finished utilizing Godot’s built-in script editor, so that you received’t want anything to get began. If you happen to choose to write down your code in a distinct window or IDE, you should use an exterior editor like Visible Studio Code, Vim or Chic Textual content. Personally, I like to recommend utilizing Visible Studio Code with the godot-vscode-plugin, though some capabilities like debugging will not be but appropriate with Godot 4.
As a remaining advice, listed here are two editor settings for the built-in script editor you would possibly need to change by way of Editor ▸ Editor Settings within the high menu:
- Disable Textual content Editor ▸ Habits ▸ Clean Scrolling. This can be a private desire, however I discover easy 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 probability of bugs. I’ll clarify why that is the case later within the tutorial.
Scripting Fundamentals
Let’s put the speculation and background info apart for now and concentrate on 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 venture’s filesystem by right-clicking res:// and deciding on New ▸ Folder.
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 foundation PlayerAvatar node and press the connect script button that appears like a scroll with a inexperienced plus signal.
This opens the Connect Node Script window, which you should use to set the preliminary settings for the script.
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 provides your script entry to variables and capabilities distinctive to that node kind.
-
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 may also create your personal 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: Mission path the place Godot will create the brand new script.
Discover that the trail factors to the scenes folder by default. Make certain to switch “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 okay 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.
This may robotically open the script editor with the brand new script opened. Press CTRL/CMD + S to avoid wasting the scene and the script after which have a look across the completely different elements of the editor.
Under is a abstract of the completely different sections:
- The toolbar positioned on the high of the display accommodates 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 aspect 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 means that you can search and discover information in regards to the built-in courses.
- Opened scripts are displayed on the high, whereas the underside record reveals the capabilities of the script you’re enhancing.
- The textual content editor shows the content material of the script, and is the primary workspace you’ll use all through this tutorial. On the high proper is a minimap, which makes it straightforward to rapidly navigate bigger scripts.
- 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 conversant in the interface, it’s time to have a look at the script itself.
Script Anatomy
Godot’s default script template makes for an excellent place to begin to construct upon additional. It even accommodates 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 probably the most used capabilities in Godot: _ready
and _process
. Because the feedback counsel, _ready
is named as soon as in the beginning of the node’s lifespan, whereas _process
is named 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.
Each capabilities begin with an underscore to mark them as personal, 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 go
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 go line within the _ready
perform to see for your self.
This may 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 kind to the output console. Save the script and run the sport by urgent F5 to see it in motion.
If the whole lot went properly, it’s best to now see the textual content being displayed on the backside. If you happen to don’t see the console, click on the Output button to toggle it on.
With the basics lined, you’re now able to faucet into the facility 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 maintain 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 should you don’t care in regards to the kind or default worth. -
: Vector2
units the kind of variable, on this case aVector2
, which has ax
andy
coordinate to carry the horizontal and vertical velocity respectively. -
= Vector2.ZERO
provides the variable a default worth.Vector.ZERO
is a continuing with a price of 0 for eachx
andy
.
Offering a sort for variables is non-obligatory in Godot, this referred to as dynamic typing. Setting the sort whereas defining new variables such as you simply did is named static typing. You need to choose 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 without spending a dime, as statically typed code runs between 25 and 100% sooner than its dynamic counterpart.
All variables all through this tutorial will use static typing to make it simpler to observe alongside and study the differing types.
Subsequent on the record is the motion velocity, which is the velocity at which the avatar will transfer horizontally in pixels per second. In contrast to the speed, it’s best to be capable 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 rapidly altering values to enhance the steadiness or really feel of your sport. The move_speed
variable is a float
, which is brief for floating-point quantity. It could actually retailer numerical values with decimal digits and is usually used for positional calculations.
Save the script player_avatar script, ensure you’ve acquired the PlayerAvatar node chosen within the Scene dock and try the Inspector on the fitting. You need to now see a brand new property named Transfer Velocity with the a price of 600.
I discovered 600 pixels per second to be a smart velocity, however you may change this worth as soon as the avatar can transfer to make the sport simpler or troublesome. Subsequent on the record is getting the participant to maneuver the mouse cursor.
For this to work, you’ll have to get the place of the cursor, test whether or not it’s left or proper from the avatar after which modify the speed accordingly each body. To get the place of the mouse cursor, change the go
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 may add the next print
name under the road you simply added:
print(mouse_pos)
This may 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.
Now you already know that’s working, take away the print line you added for testing functions and change it with the next to make the avatar transfer to the cursor:
Notice: If you happen to get an error saying “Blended 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 may robotically 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
- Calculate the gap 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 gap could be 40 pixels. Retailer this worth in a brand new variable named
x_distance_to_cursor
. - Verify if the cursor is true or left from the avatar by getting the gap calculated above and seeing if it’s a optimistic or detrimental worth. A optimistic worth means the cursor is to the fitting. Retailer this in a
boolean
variable namedcursor_right
. Aboolean
has two potential values:true
orfalse
. - 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 detrimental 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 needs to be indented with a tab and the statements finish with a colon. - The
global_position
variable is a part of theNode2D
class and shops the node’s place as aVector2
. The code applies thevelocity
to the avatar’s international place and multiplies it withdelta
to make it framerate-independent.
That was rather a lot to absorb directly! Your efforts are rewarded although, as you’ll see when operating the sport by urgent F5.
The avatar now easily follows your cursor! You might need seen somewhat quirk although: if 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.
The illustration above reveals the idea of a digital border that the avatar can’t go with a pink coloration. To implement this in code, you want the dimension of the viewport, the border width and the avatar’s place. To get the viewport’s dimension, add this line to the _process
perform, under mouse_pos
:
var viewport_size : Vector2 = get_viewport_rect().dimension
This line will get the viewport’s rectangle, which is the place and dimension of the sport window, and extracts simply the dimension
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 may 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 really restrict the avatar’s motion, modify 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:
- Reset the horizontal velocity so the avatar doesn’t transfer if there’s no horizontal velocity utilized additional down.
- If the avatar desires to maneuver to the fitting, solely enable it if its place hasn’t handed the border on the fitting. The border calculation takes the horizontal dimension of the window and subtracts the dimensions of the border from it.
- This does the identical as above, however for shifting to the left. As an alternative of taking the dimensions of the viewport under consideration, you merely use the border dimension 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.
With the horizontal motion finished, you’re now able to discover Godot’s sign system.
Alerts
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 embrace:
- The urgent of a button
- A node getting into the viewport
- The collision of two areas
- A sound impact that completed enjoying
This a strong system that means that you can maintain 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, be sure that to put it within the scripts folder.
After creating the script, it needs to be robotically opened within the script editor. Take away each the _ready
and _process
capabilities, as you received’t want them. Try to be left with simply this line:
extends AnimatedSprite2D
In distinction to the participant avatar’s Node2D
, the foundation node kind for the jumper is an AnimatedSprite2D
, which inherits from Node2D
and provides help for animations.
You’ll be utilizing a sign to detect when the avatar enters a jumper’s Area2D node. Alerts might 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 probably the most sense. Choose the Area2D node within the Scene dock and open the Node tab subsequent to the Inspector tab.
You’ll now see an inventory of alerts the chosen node helps.
Within the case of Area2D, this record is very large and stuffed 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 may present a dialog window with some choices for the connection.
By default, it’ll choose the foundation node, Jumper because the node to hook up with. That is what you need, so there’s nothing to vary 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 effective on this case. Now click on the Join button to attach the sign, this can add the brand new perform to the jumper script.
Any more, each time 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 related to a sign by the inexperienced “exit” image to the left of it. Clicking that reveals what alerts will name this perform.
To check if this truly works, change the go key phrase with the road under:
print("Obtained hit!")
By now I’m certain you already know precisely what this does: printing textual content to the console, a programmer’s finest good friend.
Save the script and open the sport scene in 2D mode. Now drag a number of situations of the jumper scene from the FileSystem dock onto the viewport, subsequent to the participant avatar.
What you simply did there may be 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 means that you can create a scene as soon as, and use it wherever you want.
With the jumpers added, press F5 to play the venture. Transfer the avatar in opposition to the jumpers and it’s best to see messages popping up within the console as anticipated.
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 in fact! 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. If you happen to bear in mind, jumper occurs to have one named 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 methodology or the superior speedy methodology. 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 should 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.
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 named you’ve seen earlier than. In essence,@onready
means that you can 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 theget_node()
perform.
Now you already know what this line does, it’s time to study in regards to 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 may add a node reference robotically, how cool is that?
You’re now one of many few people who find out about this arcane information, use this energy properly!
With the reference to the AudioStreamPlayer arrange, now you can make it play its sound impact each time the avatar hits the jumper by changing the print
name with this:
shatter_sound.play()
This calls the play
perform on the AudioStreamPlayer, which can make a pleasant glass shattering sound. Save the script and run the venture to provide it a attempt. Every time the avatar passes over a jumper, it’s best to hear the sound impact play.
If that’s working as anticipated, you may transfer on to enjoying 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 try the underside of the editor, you’ll see an inventory of obtainable animations. The default animation is aptly referred to as “default”, whereas the animation you’re setting right here is named “destroy”.
As soon as once more, it’s time to check if that is working as anticipated, so play the venture and take a look at shifting into the jumpers once more. The jumpers ought to now shatter when hit!
On to the precise self-destructing, which ought to occur after the animation finishes enjoying. There’s approach of understanding when the animation ends in the mean time, and when you may use some form of timer, a way more elegant approach is by utilizing a sign. AnimationSprite2D has an animation_finished
sign you may connect with, however connecting it by way of the editor now would end in it being emitted consistently because the default animation is enjoying 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 need 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()
methodology, which queues up the Jumper node for removing 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 advantage of connecting alerts by way of code is that it makes it straightforward to “rewire” alerts simply by enhancing a number of variables and you’ll join and disconnect them everytime you please. All of this performs into the modular nature of working with Godot and its nodes.
Play the venture 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: should 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 related 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 may set a flag on the jumper that states whether or not the jumper is energetic or not. When inactive, it shouldn’t react to any collisions.
To implement this, add the next variable under extends AnimatedSprite2D
:
var energetic : bool = true
This boolean
will act because the flag and it begins as true
, which means jumper will likely be energetic 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 energetic: # 1
energetic = false # 2
shatter_sound.play()
animation = "destroy"
animation_finished.join(_destroy_animation_finished)
Right here’s what this does:
- An if-statement that checks if the jumper is energetic earlier than doing anything.
- Set the
energetic
flag tofalse
. This may stop the code being ran greater than as soon as.
Make sure you save the script when you’re finished. With this security test added, the script is bug-free and also you’re able to make the avatar soar.
Bounce 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 shifting 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 may assign the W key, arrow up key and joystick up to an motion and test that:
if Enter.is_action_pressed("move_forward"):
move_forward()
That’s a complete lot nicer, isn’t it? This lets you reassign keys and buttons tied to an motion from the editor and even throughout gameplay. You may also assign a number of inputs to the identical motion.
So as to add an motion your self, first choose Mission ▸ Mission Settings… within the high menu to open the venture settings.
Now open the Enter Map by clicking the corresponding tab on the high.
This the place you may outline new actions. Add a soar motion by clicking the Add New Motion subject, typing “soar” adopted by clicking the Add button to its proper.
With the soar motion added, you may 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 verify.
Again within the Enter Map, now you can see the soar motion is tied to the left mouse button. Candy!
Go forward and shut the Mission 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, each time it jumps from the bottom or when it hits a jumper, that is the quantity of pixels per second it’ll 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 detrimental. The worth must be negated as optimistic Y means down in Godot, whereas detrimental 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 test 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
methodology checks for a single press, not a steady maintain, in contrast to is_action_pressed
. To complete the perform chain, add this line on the finish of the _process
perform:
_process_input()
This may name the _process_input
perform each body, which in flip checks for any inputs. Whilst you may have put the whole lot in _process
, that makes it tougher to trace down the items of code and alter them afterward. Writing clear code is a talent in itself. :]
Time for an additional check drive, press F5 to play the venture and attempt to make the participant soar.
I’d say that may be a profitable soar. It’s extra like a rocket launch in the mean 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
This can be a downward pressure 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 may push the avatar down repeatedly, simulating gravity. Run the venture once more to see if this improves the leaping. You’ll discover the avatar falls down right away and retains falling, until you click on from time to time to bounce it again up.
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 venture information utilizing the hyperlink on the high and backside of this web page.
Within the second a part of this tutorial, you’ll learn to use a finite state machine to neatly handle the avatar’s state, instantiate scenes utilizing code, make the digital camera 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!