The ship is the key to the game and most of the code will lie here.
Create a new scene with RigidBody2D as root
Add a Sprite2D and CollisionShape2D as children
Save the scene as player.tscn
Use player_ship.png as the texture of the Spite2D
We rotate the spite because in Godot, 0 degrees points right.
Select the CollisionShape2D Node
FINITE STATE MACHINES (FSM)
When using and FSM, an entity can only be in ONE state at a time. An FSM needs a number of states and what events cause a transition from one state to another.
Add a script to the Player node
define the 4 possible states
Now create the change state function
To manage state transitions
In Space there is no friction and nothing to slow you down, however in a game we want the ship to come to a stop when you let go of the keys.
Create a function to get input
If dead or initializing exit the function
move forward in current direction
rotate according to the axis pressed
Constantly check for input
update built-in physics variables
delta is the amount of time (in seconds) that passed since the previous frame.
Because a computer's frame rate can fluctuate—running at 60 FPS one moment and 120 FPS the next—moving an object by a fixed pixel amount each frame makes the game run twice as fast on faster screens or lag on slower ones.
Multiplying your movement speed by delta (e.g., position += velocity * delta) guarantees:
Framerate independence: Your game runs at the exact same physical speed whether the player is on a 30 Hz budget laptop or a 240 Hz gaming monitor.
Real-world units: Speeds are measured in pixels per second, rather than pixels per frame.
(Note: Godot's built-in physics functions like move_and_slide() on a CharacterBody2D or constant_force on a RigidBody2D factor in delta automatically behind the scenes!)
Run the scene (Press F6) You should be able to fly around the screen with WASD now
We want to setup screen wrapping so that when the ship flies off the edge of the screen it appears again at the opposite edge. Because our root node is a physics body (RigidBody2D) we cannot just change it's position we have to use a special method to change its physics properties called integrate forces
Add a variable for screensize
Calculate the screensize when the scene loads
Normally, you cannot change a RigidBody2D's position directly in code because Godot's physics engine overrides your changes. _integrate_forces() hands you a backstage pass (physics_state), allowing you to manually read and update the body's internal physics data without causing glitches or fighting the simulation.