Search code examples
godotgodot4

Too many arguments for "move_and_slide()" call. Expected at most 0 but received 1


So, I was following a tutorial for making my enemy move towards my player, and there comes a part of the script where its calls a "Move_Slide" so the enemy can move, but I get the error.

Heres my full code:

extends CharacterBody2D

# Movement speed
var speed = 100 
var player_position
var target_position
# Get a reference to the player. 
@onready var player = get_parent().get_node("Player")
 
func _physics_process(delta):
    
    # Set player_position to the position of the player node
    player_position = player.position
    # Calculate the target position
    target_position = (player_position - position).normalized()
 
    
    if position.distance_to(player_position) > 1:
        move_and_slide(target_position * speed)
        look_at(player_position)

the error is located at the part of the script "move_and_slide(target_position * speed)"

I've looked on Stack Overflow for this problem and I found a answer but this is for if i call a motion witch I don't so that doesn't help me.


Solution

  • It's because you're calling move_and_slide() on a CharacterBody2D in Godot 4. Your current code would work fine for a KinematicBody2D in Godot 3.x but in Godot 4 a KinematicBody2D was replaced with CharacterBody2D.

    A CharacterBody2D has a velocity property and it uses this property to determine the updates necessary in the move_and_slide() method. Hence, you don't need to pass in a velocity argument - you need to update the velocity property.

    Try something like:

        if position.distance_to(player_position) > 1:
            velocity.x = target_position.x * speed;
            velocity.y = target_position.y * speed;
            move_and_slide()