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
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.
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