TurboTut

Untitled

Sep 29th, 2024
405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extends CharacterBody2D
  2.  
  3. @export var speed = 100.0
  4. @export var patrol_points: Array[Marker2D] = []
  5. var current_point_index = 0
  6.  
  7. @onready var detection_area: Area2D = $Area2D  # Reference to the detection area
  8. var player: Node2D = null  # Reference to the player, initially set to null
  9.  
  10. func _ready() -> void:
  11.     if patrol_points.size() == 0:
  12.         print("No patrol points assigned!")
  13.        
  14.     detection_area.body_entered.connect(_on_player_detected)
  15.     detection_area.body_exited.connect(_on_player_lost)
  16.  
  17. func _on_player_detected(body: Node2D) -> void:
  18.     if body.name == "Player":
  19.         player = body  # Set the player reference when detected
  20.  
  21. func _on_player_lost(body: Node2D) -> void:
  22.     if body == player:
  23.         player = null  # Reset the player reference when they leave
  24.  
  25. func _process(delta: float) -> void:
  26.     if player:
  27.         chase_player()  # If a player is detected, chase them
  28.     else:
  29.         patrol()  # Call the patrol function every frame
  30.     move_and_slide()  # Apply movement to the enemy
  31.  
  32. func chase_player() -> void:
  33.     velocity = (player.global_position - global_position).normalized() * speed
  34.    
  35. func patrol() -> void:
  36.     if patrol_points.size() > 0:
  37.         var target = patrol_points[current_point_index].position
  38.         velocity = (target - position).normalized() * speed
  39.  
  40.         if position.distance_to(target) < 10.0:
  41.             current_point_index += 1
  42.             if current_point_index >= patrol_points.size():
  43.                 current_point_index = 0
  44.  
Advertisement
Add Comment
Please, Sign In to add comment