Loading...
Loading...
Program a simple enemy that patrols an area and chases the player when detected.
Create the enemy scene. Add a 'CharacterBody2D' node as root, rename to 'Enemy'. Add 'Sprite2D' and 'CollisionShape2D' for the enemy body. Add an 'Area2D' child called 'DetectionZone' with a 'CollisionShape2D'. This area will detect when the player enters the enemy's detection range.
Set up patrol waypoints. Create a 'Path2D' node as a child of Enemy. Draw a path using the Path2D's curve where you want the enemy to patrol. Add a 'PathFollow2D' child to move along the path. In the Enemy script, reference these: `var path_follow = $Path2D/PathFollow2D`.
Implement patrol movement. In _physics_process: `if state == 'patrol': path_follow.progress += speed * get_physics_process_delta_time()`. Create an enum or string variable for states: `var state = 'patrol'` (other states: 'chase', 'attack'). The enemy will automatically follow the path.
Detect the player. In the DetectionZone Area2D script: `func _on_body_entered(body): if body.name == 'Player': enemy.chase_player()`. In the Enemy script, create `func chase_player(): state = 'chase'`. Add a timer or distance check to stop chasing when player leaves range.
Implement chase behavior. In chase state: Calculate direction to player: `var direction = (player.global_position - global_position).normalized()`. Move toward player: `velocity = direction * chase_speed`. Add collision detection to stop before hitting the player. When player is out of range or dead, return to patrol: `state = 'patrol'`.