Search code examples
artificial-intelligencegodotgodot4

CharacterBody2d jittering while moving and not moving to correct place in Godot 4


I am trying to make a 2d infinite game were you run around through dungeons and kill monsters. I am currently working on the AI for the enemies (skeletons) but

  • they keep telepoting to the player when you jump
  • they are moving VERY slow when on the ground
  • while the player is in midair the enemies will jitter around and go through the floor

The code that I used to try and make the enemies only move on the x axis is here:

extends CharacterBody2D

var speed = 1000
var target = position

func _physics_process(delta: float) -> void:
    move_towards_closest_player()

func move_towards_closest_player() -> void:
    var closest_player = get_tree().get_nodes_in_group("player")[0]
    var closest_distance = 1000000000000000000
    
    if closest_player == null:
        closest_player = get_tree().get_nodes_in_group("player")[0]
    
    for player in get_tree().get_nodes_in_group("player"):
        if player != null:
            var distance = abs(player.global_position.x - global_position.x)
            if distance < closest_distance:
                closest_distance = distance
                closest_player = player
    
    if closest_player != null:
        var direction = (closest_player.global_position - global_position).normalized()
        move_and_collide(direction * speed)

The code above is giving no errors.


Solution

  • var direction = (closest_player.global_position - global_position).normalized()
    move_and_collide(direction * speed)
    

    in those lines you're calling the move_and_collide() to move the enemies on both X and Y axis

    change it from:

    move_and_collide(direction * speed)
    

    to:

    move_and_collide(Vector2(direction.x * speed,0.0))
    

    also if you're moving the enemies only on one axis .normalized() is not needed