Skip to content

Commit

Permalink
Fix multiple target acquisition, and crash after destruction
Browse files Browse the repository at this point in the history
  • Loading branch information
jspahrsummers committed Jun 26, 2024
1 parent d531cd9 commit deb4c28
Showing 1 changed file with 17 additions and 13 deletions.
30 changes: 17 additions & 13 deletions ships/pirate.gd
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,22 @@ var direction_tolerance_rad: float:
get:
return deg_to_rad(direction_tolerance_deg)

func _find_a_target():
func _acquire_closest_target() -> void:
var ships := get_tree().get_nodes_in_group("ships")
ships.erase(self)
return ships[0] if ships.size() > 0 else null

var closest_ship: Ship = null
var closest_distance := self.detection_range

for ship in ships:
var distance := global_transform.origin.distance_to(ship.global_transform.origin)
if distance < closest_distance:
closest_distance = distance
closest_ship = ship

self.set_target(closest_ship)

func _physics_process(delta: float):
if self.target == null:
self.set_target(_find_a_target())

if self.target == null:
self.current_state = State.IDLE

Expand All @@ -49,10 +56,8 @@ func _pointing_in_direction(direction: Vector3) -> bool:
return current_direction.angle_to(direction) <= direction_tolerance_rad

func idle_behavior(_delta: float):
if self.target == null:
return

if player_in_range():
self._acquire_closest_target()
if self.target != null:
current_state = State.PURSUE

func pursue_behavior(_delta: float):
Expand Down Expand Up @@ -83,11 +88,10 @@ func retreat_behavior(_delta: float):
if distance >= preferred_distance:
current_state = State.ATTACK

func player_in_range() -> bool:
var distance := global_transform.origin.distance_to(self.target.global_transform.origin)
return distance <= detection_range

func _integrate_forces(state: PhysicsDirectBodyState3D) -> void:
if self.target == null:
self.current_state = State.IDLE

if self.current_state == State.IDLE:
return

Expand Down

0 comments on commit deb4c28

Please sign in to comment.