Godot version 4`
My player is the white one and my enemy is the black one.
//script for me enemy
extends CharacterBody2D
@onready var player = $"../Player"
var _player = null
const CHASE_SPEED = 200.0
const GRAVITY = 980.0
func _physics_process(delta):
# Apply gravity
if not is_on_floor():
velocity.y += GRAVITY * delta
if _player:
var player_direction = (_player.global_position - global_position).normalized()
velocity.x = player_direction.x * CHASE_SPEED
else:
velocity.x = 0
# Apply movement
move_and_slide()
# Optional: Flip the sprite based on movement direction
if velocity.x < 0:
scale.x = -1
elif velocity.x > 0:
scale.x = 1
func _on_detect_player_body_entered(body):
if body.name == "Player":
_player = body
func _on_detect_player_body_exited(body):
if body.name == "Player":
_player = null