how does move_and_slide work? I set up a velocity with speed as such velocity.x = speed right direction and -speed in the left direction. my character is not moving but staying in place, The animation is working fine with input but something is wrong with moving the player, how do I use it, or how is it supposed to work? i have a characterbody2D with collsionshap2D on my player, my script is on my characterbody2D
func _physics_process(delta: float) -> void:
# Apply gravity when not on the ground
if not is_on_floor():
velocity.y += gravity * delta # Apply gravity to the vertical velocity
else:
velocity.y = 0 # Reset vertical velocity when on the ground
# Handle movement and attack
if not is_attacking:
player_move() # Handle movement
player_attack() # Handle attacking
# Move the player using move_and_slide
move_and_slide() # Move the character
func player_move():
# Reset is_moving at the beginning
is_moving = false
# Handle horizontal movement
if Input.is_action_pressed("left"):
velocity.x = -speed # Move left
$AnimatedSprite2D.flip_h = true
is_moving = true
elif Input.is_action_pressed("right"):
velocity.x = speed # Move right
$AnimatedSprite2D.flip_h = false
is_moving = true
else:
velocity.x = 0 # Stop horizontal movement
# Play run animation if moving, otherwise play idle animation
if is_moving:
$AnimatedSprite2D.play("run")
else:
if not is_attacking:
$AnimatedSprite2D.play("idle")
I think your method player_move could run parallel to your physics_process function or your speed isn’t set to a large enough value?
At least that’s the only logical explanation I can come up with. Can you try to add a return type (for example bool or int) to your function player_move (or await your player_move function or just put the code directly in your physics_process function)? In theory that should force the script to first run the player_move function and then the rest of the _physics_process part.
By the way you can simplify your code:
#
func physics_process(delta):
...
# player move part
velocity.x = Input.get_axis("left", "right") * speed
is_moving = velocity.x != 0
...
# or await
func physics_process(delta):
...
await player_move()
...
# or use a return type
func player_move() -> bool :
velocity.x = Input.get_axis("left", "right") * speed
is_moving = velocity.x != 0
...
return true
i found the problem, my move_and_slide was working but I had an issue with it in level scene, which is kinda weird, why my player can move in player scene but not in level scene? i solved this issue but now I’m facing a new one, player is not able to move in level scene, I tested it with my ground objects and they don’t seem to bother player, they can collide perfectly with player, I also turned off all collisions with backgrounds and text just in case, still player cant move for some reason