In this part of the tutorial, you will learn how to rotate our spaceship! 🚀
check the video bellow to see the final result of this section :
You will:
learn how to set up input bindings in Defold.
Create your first script and attach it to a game object.
Get introduce to Defold's adressing and messaging system.
So In the editor, open the folder input folder, then click on "game.input_binding". A window will open.
This is where we will configure our input system.
Then in the "Key Triggers" section, click on the "+" button to add a new input.
add the Up, Right and Left button. In the collum section fill each line with the names "left, right and up". These actions will be linked to the corresponding inputs.
If you already have some key triggers, click on the "-" button to delete them.
You should have this 👆 configuration at the end.
Ok now, right-click in the main folder section, then select "New" and click on "Script". Name it "ship", and finally, click "Create Script". A new file will appear in the main folder.
Then, go back to the "main.collection" window. In the outline, right-click on the ship Game Object.
Finally, select our new script file "ship.script". Now, our script is linked to our ship Game Object.
Open the script. As you can see, there are already a lot of lines of code. You can delete them all...
Yeah, we will start from a blank page!
Before writing any code, it’s essential to understand how the game loop works—not just in Defold, but in most game engines!
A game engine follows a continuous cycle called the game loop, which ensures that the game runs smoothly by updating and rendering everything on the screen. This loop consists of three main phases:
Initialization (Init) – This phase happens once when the game object is created. It is used to set up variables, load resources, and prepare everything needed for the game object.
Update – This phase happens continuously, many times per second. Here, the game logic is updated: movement, collisions, input handling, and other dynamic behaviors.
Finalization (Final) – This phase occurs when the game object is about to be deleted. It allows you to clean up memory, save data, or release resources.
In Defold, these phases are handled inside a script attached to a game object. A script file contains functions that match these phases:
init(self) → Called once when the object is created.
update(self, dt) → Called every frame, where dt (delta time) is the time passed since the last frame.
final(self) → Called when the object is removed.
This loop keeps repeating as long as the game is running, ensuring smooth gameplay.
So, we will start by rotating the spaceship using the keys we defined together in the key bindings.
Let's start by adding the init function in Defold. This function is where we will initialize the variables we need to move our spaceship.
The self keyword refers to the instance of the object that is using the script—in this case, our spaceship.
Let's declare a variable self.angle in the init function — this variable will be used to update the spaceship's rotation.
Have you noticed the keyword used? self followed by a "." and then angle.
From now on, angle will be a property specific to the script attached to our Game Object.
Next, we will declare two local variables in the init function: angle_rad and rotation.
angle_rad will store the conversion of the angle from degrees to radians using the function math.rad(), which takes an angle in degrees as a parameter.
rotation will store a rotation vector using the function vmath.quat_rotation_z(), which takes an angle in radians as a parameter.
Now, we will apply our angle to our spaceship.
To do this, we need to modify the rotation property of our Game Object.
In 2D, objects are usually displayed on the XY plane (meaning they move along the X and Y axes).
Rotating around the X or Y axis would tilt the object in a 3D perspective, which is not useful for a purely 2D game.
Rotating around the Z-axis makes the object spin within the XY plane, which is the expected behavior for a normal 2D rotation.
💡Note: In Defold, rotations are represented as quaternions, and since we're rotating the spaceship around the Z-axis, we use vmath.quat_rotation_z().
However, right now we have a problem: our rotation angle is already set to 0.
But the spaceship doesn't seem to be facing the angle of 0. No, it's actually oriented at an angle of 90 degrees. Check the image below to see what I mean.
As you can see, 90 degree is facing toward the top, 0 is for the right, 270 is for the bottom and 180 is for the left.
We need to adjust our spaceship’s angle to make it face the correct direction. However, instead of modifying the Game Object, we will adjust the angle of its components.
To access the components of the Game Object, click on "ship_spr".
Next, modify the rotation angle on the Z-axis to -90 for both "ship_spr" and "effect_spr".
The sprites should now be oriented to the right.
The sprites are now oriented in the correct direction. Now, we need to position "effect_spr" correctly. ajust the "effect_spr" position to : x : -45.0, Y : 0.0 and Z : -0.1
Open "ship.script" again. Now, we are going to add the `update` function.
We will reuse the two lines of code for `angle_rad` and `rotation`, as they will be useful for updating the spaceship's rotation.
We will now use the `set_rotation` function, which is a function of the Game Object (go). We will pass the `rotation` variable to it.
This will update the rotation of the ship's Game Object based on the value we calculated for `rotation`.
Let's do a test before updating the rotation:
We will update the `self.angle` variable first. This will allow us to check if the angle is changing as expected before applying it to the rotation.
Let's modify the spaceship's angle by 90 degrees per second. Now, test it by pressing F5 to run the game and see the result.
Great! Now the spaceship is rotating on its own.
But what if we made the rotation happen based on key presses instead? Let’s implement that and allow the player to rotate the spaceship manually using the keyboard in Defold.
To do this, we can check for specific key presses in the `update` function and modify `self.angle` accordingly.
If we want to receive key input in our script, we need to indicate this in the init function of our script.
We do this by using acquire_input_focus, which we will add at the beginning of our init function via msg.post(). This function is part of Defold's message system.
Here’s what it looks like in code:
This will allow the script to start receiving input from the keyboard.
In Defold, components (scripts, game objects, GUI, etc.) communicate using messages.
It’s an asynchronous system to send commands or receive events.
Use the msg.post() function:
msg.post(receiver, message_id, message_data)
Parameters:
receiver: who should receive the message
Example: "." (yourself), "#sprite" (a component), "/enemy#script" (another object)
message_id: the message type
Example: "play_animation", "acquire_input_focus"
message_data: (optional) a table with extra info
Example: { id = hash("idle") }
This game object
"."
msg.post(".", "acquire_input_focus")
Component in the same game object
"#component"
msg.post("#sprite", "play_animation", {...})
Component in another game object
"/go#component"
msg.post("/enemy#script", "hit", { damage = 10 })
Messages are received using the on_message() function in a script:
function on_message(self, message_id, message, sender)
if message_id == hash("hit") then
-- handle it here
end
end
Let's return to the init function and add another variable to our script, called input.
This variable will be a vector3, meaning it will have X, Y, and Z values. We will update this variable based on key presses.
Here’s how we can declare it:
Now, we'll update the input variable based on the key presses in the update function.
Example: If I press the left arrow, we will update self.input.x and assign it -1. Otherwise, if I press the right arrow, we will update self.input.x to 1, and so on.
In the init function, add the following line of code. It's not really necessary for now, but if you want to make sure that the rotation value of the game object starts at zero, you should write this.
Now, let's add Defold's on_input function. This is the function where we will handle key presses.
Now, add the following code.
action_id is a parameter of on_input that helps us determine which key the player pressed. Notice that I wrote hash("left"). hash is part of Defold's scripting system.
Here, by pressing left, we set the input.x to -1.
Let's do the same thing for the right key:
Now, in the update function, delete the folowing line :
And let's create a condition to check if the x value is equal to 1. If that's the case, we will decrement the spaceship's angle. This way, it will rotate to the right...
If you run the application and press the right arrow key, the spaceship will indeed rotate, but it won’t stop.
What we need to do is, at the end of the update function, reset self.input. At the end of the update function, assign a new vector3 to self.input.
Restart the game, and now the spaceship will stop when you release the key, because input is reset to zero.
Let's also account for pressing the left arrow key, meaning when self.input.x is equal to -1.
Let's run the game! Now the spaceship rotates and stops as soon as we stop pressing the keys.
Great! Our spaceship can now rotate using our key input system! Now, let's move on and write the code that will allow us to move our spaceship in the direction it's facing. We will do that in Part 3. !