Player 8 Directional Movement for Godot 4.1

David

Player 8 Directional Movement for Godot 4.1

Below is the script for the basic 8-directional movement for Godot 4.1. I am using Godot 4.1.2 stable version. You will need to set up your own animations for your sprite and will need to change the animation naming conventions for what works for you. As well as setting up the input map in the project setting for Up, Down, Left, and Right.

For this, I have a very basic scene consisting of a CharacterBody2D as my base node, with an AnimatedSprite2D, CollisionShape2D, and a Camera2D as children of the base node.

The base node CharacterBody2D has been renamed ‘player’ with a script attached. In that script, you will input the following.

FYI, you can copy and paste but know that there will need to be some editing due to the constraints of publishing through this website.

extends CharacterBody2D
var speed = 100
var player_state
func _physics_process(delta):
    var direction = Input.get_vector("left", "right", "up", "down")
    if direction.x == 0 and direction.y == 0:
        player_state = "idle"
    elif direction.x != 0 or direction.y != 0:
        player_state = "walking"

    velocity = direction * speed
    move_and_slide()
    _play_animation(direction)
func _play_animation(dir):
if player_state == "idle":
$AnimatedSprite2D.play("idle_s")
    if player_state == "walking":
if dir.y == -1:
$AnimatedSprite2D.play("walk_n")
if dir.y == 1:
$AnimatedSprite2D.play("walk_s")
if dir.x == -1:
$AnimatedSprite2D.play("walk_w")
if dir.x == 1:
$AnimatedSprite2D.play("walk_e")
if dir.x > 0.5 and dir.y < -0.5:
$AnimatedSprite2D.play("walk_ne")
if dir.x > 0.5 and dir.y > 0.5:
$AnimatedSprite2D.play("walk_se")
if dir.x < -0.5 and dir.y > 0.5:
$AnimatedSprite2D.play("walk_sw")
if dir.x < -0.5 and dir.y < -0.5:
$AnimatedSprite2D.play("walk_nw")