Help about programming top down mouvement

Godot Version

4.2.1

Question

Hi, i’m new to game dev so i followed a tutorial
https://www.youtube.com/watch?v=1TU2X37wPes and idk why nothing work, i tried to use basic player mouvement template but don’t work either, my sprites can’t move

here my scripts :

extends CharacterBody2D

const SPEED = 300.0
const JUMP_VELOCITY = -400.0

Get the gravity from the project settings to be synced with RigidBody nodes.

var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)

func _physics_process(delta):
# Add the gravity.
if not is_on_floor():
velocity.y += gravity * delta

# Handle jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
	velocity.y = JUMP_VELOCITY

# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction = Input.get_axis("left", "right")
if direction:
	velocity.x = direction * SPEED
else:
	velocity.x = move_toward(velocity.x, 0, SPEED)

move_and_slide()

Howdy! It appears that your code is the default code for CharacterBody2Ds. This only handles platformer (Like Mario) style games, not Top-Down. Follow the tutorial again, but this time select “Node: Default”, add a sprite and collision into the player, and then add this:

extends CharacterBody2D

@export var movement_speed : float = 500
var character_direction : Vector2
var sprite = AnimatedSprite2D


func _physics_process(delta):
	character_direction.x = Input.get_axis("ui_left", "ui_right") #Left and right movement.
	character_direction.y = Input.get_axis("ui_up", "ui_down") #Up and down movement.
	character_direction = character_direction.normalized() #Stops diagonal movements from going faster.

	#Flips sprite.
	if character_direction.x > 0: sprite.flip_h = false
	elif character_direction.x < 0: sprite.flip_h = true
	
	#Adds walking/idle animation and moves player if the value is not 0.
	if character_direction:
		velocity = character_direction * movement_speed
		if sprite.animation != "Walking": sprite.animation = "Walking"
	else:
		velocity = velocity.move_toward(Vector2.ZERO, movement_speed)
		if sprite.animation != "Idle": sprite.animation = "Idle"

	#Always add this line of code for your character to move.
	move_and_slide()

I added some notes so you can understand this better, and changed the code up a bit. Good luck, and good day!

2 Likes

thanks you

I’ve used CharacterBody2D s the root node for some of my top down games without issue. :man_shrugging:

You mean the CharacterBody2D basic movement? That’s for specifically for platformers, although it could be adjusted to be top-down. Did you adjust the code or slap it in the project?