A Guide to Third-Person Controllers
Reorganizing the project Before moving on, I would like to reorganize the project folder a bit. Then drag the Main. Repeat the previous operations and create a folder called Entities. For now, the only entity we have is the player. Then, under Entities, create a folder named Player, and drag the player. The final result will be this: Another thing we can do is rename the root node to Root.
To do this, select it and then click again on the name to enter editing mode, or right-click on it and press Rename. After editing, our scene will have this structure: Press Play to check that everything is all right. The project should work properly because Godot will automatically update all references to the files we have moved.
Setting up player node for movement To move the player, we will use the KinematicBody2D node type. KinematicBody2D nodes are special types of physical bodies that are meant to be user-controlled. First, add KinematicBody2D as a child of Root: Now, move Sprite into it and rename KinematicBody2D to Player: An important thing to know is that the position of a node is always relative to its parent node.
Since Player will be the object we move and not just Sprite , we will have to set the position of Sprite to 0,0 , so that it is in the same position as the Player node. Now we can move Player to the center of the screen at the position , If we look at the Player node, we see that there is a yellow triangle at his side. This warning tells us that we have not defined a collision shape for the KinematicBody2D.
You use Input Mapping by creating named input actions, to which you can assign any number of input events, such as keypresses or mouse clicks. A new Godot project includes some default actions already defined. By default, these actions are associated with the keyboard arrow keys and the joypad D-Pad events. We want to add the ability to move the character using the joypad analog stick as well.
To do this, for each of these actions we will add the relative joypad axis event. You will be shown a window to choose the device and the axis to be added: choose Device 0 and Axis 0 — Left Stick Left and press Add. The deadzone corresponds to how much a joypad stick or trigger needs to be moved before the action is considered pressed. Reduce this value to 0. Repeat these operations for the other input actions. The final result will be this: The movement script Right-click on Player and select Attach script.
You can pass data, known as parameters, to a function, and it can return data as a result. A class serves as a template for creating objects.
As we saw in our first Godot project , in GDScript each script file represents a class. When you attach a script to a node, you are creating an instance of that class.
If reading the explanation you have any doubts, you can go to the GDScript basics page on the Godot website to learn more about the features of the language.
Player movement speed In GDScript, anything from a to the end of the line is ignored and is considered a comment. If you change the variable in the editor, its new value is saved in the scene file. In our script we are overriding it to process player movement. This function is called during the physics processing step of the main loop.
Since the rate is constant, the delta parameter of the function, which represents the time elapsed since the last physical processing, should be constant too. GDScript uses indentation to indicate a block of code. Vector2 is a 2-element structure used to represent positions in 2D space.
You can access its values using the x and y properties. We will use the direction variable to store the direction in which the player wants to move. Looking at these two lines, we learn a few things: the dot operator. In GDScript, a string is enclosed by double quotes.
What does this code do? In a joypad, for example, the further away the stick is from the dead zone, the closer the value will be to 1. If the action is mapped to a digital control like a key or a button, the value returned will be 0 not pressed or 1 pressed. When we press a single key, we get a direction vector of length 1. For example, for right movement, direction has a value of 1,0. But if we press Right and Up simultaneously, the direction vector will have components 1,-1 , and its length will be about 1.
So, we should perform a so-called normalization operation, that is, compute a vector of length 1 that points in the same direction of the original vector. On the contrary, when we use the analog stick, this problem does not occur. So we have to check if we have a non-normalized diagonal movement, and in that case normalize it. The if statement is used to check if a condition is true or not, and based on that, decide whether to execute a code block.
The condition we check is whether the absolute value calculated with the abs function of both the x and y components of direction is equal to 1. If it is true, it means that the player input is a non-normalized diagonal movement. In this case, the length of the vector will be different from 1, so we will simply use the normalized function of Vector2, which will return a normalized vector with the same direction.
We simply calculate it as speed multiplied direction which gives us the velocity multiplied by the elapsed time delta. We will store the result in a new variable called movement. We will see in the next tutorial that if there are other CollisionObject2D nodes, the character will stop if it collides with them.
Testing the game Run the game. You can move the character by pressing the arrow keys. If you have a joypad, you can test the movement with both the D-Pad and the analog stick.
Conclusions In this tutorial we have learned to get player input and use it to move the character on the screen. Did you enjoy this article? Then consider buying me a coffee! Your support will help me cover site expenses and pay writers to create new blog content.
Godot Engine – Movement and Rotation basics
There are multiple approaches you can take to move objects. There are generic ways for all objects to be moved, however some nodes require different functionality to be moved. Such as the KinematicCharacter node. The reason for this is because it uses functionality for collision with slopes.
Moving an object using the AnimationPlayer node To start off simple, we will move a object without the need to write any code. You can simply do this by adding a AnimationPlayer node in the node tree of a object. View of the scene tab with the AnimationPlayer node selected After you have selected the AnimationPlayer node, you can select the Animation tab at the bottom of the screen.
Press the Animation button and select New to create a new animation. After you have created a new animation file. You now see key icons next to properties of other nodes. These are shown as long as the Animation window is open. So they may disappear if you select a node that is currently using a different window, you can easily switch back to the Animation tab to get it back. Select the position key if you want to record the current position.
After keying the position, you can move the slider to the according time and do another key for the selected time in the animation tab. Moving an object directly The easiest way to move an object in Godot is by setting the position directly. This is done by setting the position property of a node. For a Node2D this will consist of a X and Y coordinate.
For a Node3D this will also have a Z value. This can be useful if you want to move a value to a specific target at a fixed speed. You can either choose to use the Tween node or to use code to move it between the points. Or you could use the lerp method to linearly interpolate the position of an object. Quite useful if you want to move an object between point a and b. Ensuring it always meets the target. Example of using linear interpolation to move between two points. Credits to Robert Norenberg for the knight asset First we get some points to move between.
In this case I get the points based on the screen size. This sample is based on the video above. Which I use to count time. Then I store the direction and total move duration. The main reason for needing the moveDuration is so we can tell how long it should take for the lerp to go from point a to b. The timeDirection just defines what direction time goes in. So we can move backwards.
The time variable is what is used to execute the lerp between point a and b. For instance, you have value 5 and value How far is 7 between those values? Move object using a tween node Moving the character sprite using a tween node with a exponential transition The tween node is likely the quickest way to do any type of tween movement in Godot. Aside from using plugins. Which we will get to later.
You can choose to add a tween them during runtime, or you can attach them directly to the node in the editor. In our case we add the node in GDScript. There is only limited customization in the inspector, this means you are required to configure a Tween through code. One of the biggest benefits of using the Tween node is being able to set an ease type, and you can easily use yield or subscribe to a signal to get a callback for when a tween is complete.
Inspector of the Tween node, you can see that it is lacking any type of interpolation settings. If you are interested in all the available easing types. This website gives a good representation of the most common tween types. Personally I always come back to this site if I cant remember how a specific easing type works. Moving an object using Path2D and PathFollow2D Paths are a good alternative for tweens if you need a sequence of movements along a path. Example of the knight sprite being parented to a PathFollow2D node Creating a path in Godot is relatively easy.
You create a Path2D node, afterwards you select it. Upon selection you will see additional options at the top of your 2D view. Afterwards there is an add point button, remove point button and close curve button to make it a full loop.
Based on the total length of the path and the time. This ensures it gets updated during the physics step. Move and collide : breakout code sample As you can see in this sample. It then uses the vector. Another benefit is that it helps the character stay on fast moving platforms.
The platforms are also using a KinematicBody2D and animator to move them. This code has been partly taken from the Kinematic Character 2D demo. First, get the player's input. Apply gravity. DOWN , Vector2. Most of these methods will also be applicable in 3D, as it is just a matter of adding another axis. Hope this article was of use to you. If interested, check out any of the other articles available on the site.
All right so we got all of our objects here pretty much set up and ready to go. So think of it sort of as a gun for example. In fact, many games use raycast for their guns. When you shoot a gun it goes and the bullet goes along from the muzzle in the direction it is facing. And if it hits something, it gets detected pretty much. And you can see this white line right here and this white line pretty much shows how far our raycast is gonna go.
So pretty much anything that intersects this white line right here will be detected by the raycast. So it is gonna be facing in our forward direction here, not down. We can now have the line pointing out this direction from our player.
Godot 3 – Most common ways to move an object
All right so that is pretty much it. We got everything here set up and ready to go. Now if we go back to the main scene, what we can do is in fact go ahead and drag in our enemy so go to the file system, drag an instance of the player.
And there we go. And yeah, now what we can do is press play and see how it looks. Camera Setup Welcome back everyone. Have the ability for a camera to orbit around our player when we move the mouse around. So, we got a player scene right here inside of the main scene. This one is gonna be called a camera orbit right here.
First up, we have look sensitivity. So variable lookSensitivity and this is going to be a float and by default will equal Now, lookSensitivity is just gonna be basically how fast this the camera gonna rotate based on how fast our mouse moves.
All right, then we need a minLookAngle. So how far up can the camera rotate. Now what we need to do is keep track of the mouse delta and the mouse delta is pretty much each frame, how fast and in what direction did the mouse move? So the parent node of camera orbit is the player kinematicbody node.
So if we have moved the mouse around this frame, then we can just go mouseDelta equals event. This function gets called every single frame so if the game is running at 60 FPS, this will be called 60 times a second. So what we want to do here is get the rotation pretty much. What rotation are we gonna be applying to the camera and the player? So for the X, this is gonna be mouseDelta. So, mouseDelta. Now, we just need to multiply this by the lookSensitivity and multiply it by delta as well And multiplying it by delta just gives us a bit of a smoother camera rotation.
Now, we need to apply this rotation to the camera and to the player. This is the rotation when we move the mouse up and down. We wanna clamp this position. We wanna clamp the rotation around the player. And the clamp function is really handy because we can give it a three values. X and then we give it a minimum and a maximum value. So a min is gonna be our minLookAngle and max is gonna to be our maxLookAngle as well.
So for that, we can just go a player. And finally, we just need to clear the mouseDelta. You can, of course, tweak this to however you want, if you want the camera to move independently of the player as well.
You might also notice something here, is that, the mouse is still here. So what we can do is basically lock the mouse cursor. So at the start of the game, this mouse is hidden and it is locked to the screen which is really what you want for these games that control the camera with the mouse. And what we want to do here is, hide the mouse cursor.
Visible is what we have right now and the mouse is visible we can see it. Hidden is when the mouse is hidden on screen but it can still move around. Confined is when it is pretty much confined to the screen but we can still see it. So we got mouse mode captured here. All right, great.
Have the ability to move around with the WASD keys, jump with the space bar and yeah. So to begin, what we need to do is set up our actions because whenever our player wants to move, we need to know which keys on the keyboard do what things. What do we need to press in order to move forward, back, left, right, jump.
Then go Project Settings. And in here we want to go to the Input Map tab. An action can be a key press, a mouse-button click or anything with a durma press brake problems controller, stuff like that.
Press enter to create a new action. Okay, so we got our six new actions over here. And then we can just enter in the key that we want.
Godot Tutorial – Part 5: Player movement
There we go, hit OK. We can do move backward here to S. And for attack this is gonna be a mouse button. And then Mouse Button Index is gonna be left mouse here. All right, we can close out of that. We can remove this base template stuff here.
So, first up we need to know our current HP. Then our maxHP, which is gonna be the max amount of HP we can get. Then we all know how much damage we do. So whenever we attack an enemy, how much damage are we gonna be dealing to them? And then we also need to know for attacking, how often can we attack? So every. And this is gonna be tied to the length of our animation.
We also need to know that the lastAttackTime. And the lastAttackTime here is just going to be in terms of milliseconds from when we last attacked. And after this, we needed to get on with some of the physics stuff. So, first of all, our moveSpeed. Which is gonna be a float. Then we have jumpForce. So how much force is gonna be applied upwards when we press the space bar to jump.
This will be a float and it will equal And after this we also need to know gravity because we are gonna have gravity being applied to us. This is gonna be of type float. Of type Vector3 equals a new Vector3. And velocity is just gonna be our basic velocity.
Where are we moving, which direction and at what sort of speed. So we need to keep track of that. And finally some of our components. We need to know the camera and the attack raycast. So, for the camera this will be an onready var because we are gonna be getting this when the node is initialized. And we want to get the CameraOrbit object, which holds our camera script.
Okay, so we got the camera. Then we need to get the attack cast. And we need to get the attackRayCast right here. Now what we can do is start on actually moving the play around inside of the physics process function. Now the physics process function is a function which gets called 60 times a second. And this is just in order to maintain consistency with physics. And delta here is the time between each frame.
So, what we want to do here, first of all, is set our x and z velocity to zero. So vel. And vel. And then after this, we wanna be able to get our input vector. And the input vector is gonna be filled in whenever we press on a button, WASD. So, var input equals Vector3. And now we need to check each of our key presses.
So, if an action is pressed, the move forwards, backwards, left or right action, we need to modify this input vector right here.
How to make a 3D RTS in Godot 3.1 part 1 – Camera Movement and Basic Unit Movement
So, we can go if Input. So we need to increase z here by one. Vector A vector represents a magnitude and direction. In a game engine, a vector is used to represent a position or a direction. The world is where we put all game objects and it is where the game runs. If we add the global right vector i. If you are coming from Unity, take note that Godot has a slight difference in the axes compared to Unity. The forward direction is not positive z, but it is negative z. So when we export from blender, make sure the forward is -z forward and y is up.
Forward is inverse z Every object in the game world also has its own position and a direction. This position and direction is stored as a Matrix. You only need to understand that every object has a transformation matrix which represents the position and its orientation also the scale, but leave it for now. So if we know the transform of a game object, we can get its position and its direction.
We get the position from its origin and orientation from its basis. Enough talk on vectors and matrices, let us jump into action Moving in global axes This code moves the object on the world x axis. Instead of using this code, godot provides a simpler method for doing this. Even if we rotate the object, it just moves along the world x axis because the object is moved in global x axis. Global transform is independent of local position and rotation.
For that we need to know the local right direction vector of the object. Godot engine has easy and simple methods for doing this.
The passed Vector3 delta,0,0 is converted to its local space internally.