How to Do First Person Movement in Godot 4!

How to Do First Person Movement in Godot 4!

Watch the Tutorial on How to Do First Person Movement in Godot 4!

Creating smooth and responsive first-person camera movement is an essential aspect of many types of games, from first-person shooters to exploration games. Godot 4 offers powerful tools for implementing camera controls, making it easier than ever to create immersive first-person games. In this blog post, we’ll walk you through how to set up a basic first-person camera movement system in Godot 4 using the code provided.

Getting Started…

You’ll need to create a new project in Godot 4 and create a new scene with a player character and a camera. The code we’re using is an extension of the CharacterBody3D node, which is a useful node for creating player-controlled characters in 3D games. You can add this code to your CharacterBody3D script and adjust the variables to your liking.

The first variable we define is MainCamera, which is set to reference the %MainCamera node in our scene. This node represents the camera that will be controlled by our script. We also define two constants, SPEED and JUMP_VELOCITY, which control the speed of movement and the jump height of our character.

The next variables we define are CameraRotation and MouseSensitivity. CameraRotation is a Vector2 that keeps track of the rotation of our camera in X and Y directions. MouseSensitivity is a constant that controls the speed at which the camera rotates in response to mouse movement.

Let’s Code

In the _ready() function, we set the mouse mode to MOUSE_MODE_CAPTURED, which hides the mouse cursor and captures mouse input. This allows us to control the camera with the mouse.

In the _input(event) function, we check if the “ui_cancel” action is pressed. If it is, we toggle the mouse mode between MOUSE_MODE_CAPTURED and MOUSE_MODE_VISIBLE. We also check if the event is an InputEventMouseMotion event, which is triggered when the mouse is moved. If it is, we pass the relative movement of the mouse to the CameraLook() function.

The CameraLook() function takes a Vector2 argument representing the mouse movement. First, we add this movement to our CameraRotation variable. Then, we reset the transform basis of our character and camera nodes to their default values. We then rotate the character in the Y direction by -CameraRotation.x and the camera in the X direction by -CameraRotation.y. Finally, we clamp the Y rotation of our camera between -1.5 and 1.2 to prevent the camera from flipping over.

We Did it!

And that’s it! With these few lines of code, you can create a basic first-person camera movement system in Godot 4. Of course, there are many ways to extend and customize this system to suit your needs, but this should give you a solid starting point. Happy game development!

Follow along on Youtube!

Check out my Templates!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *