behavior_agent.gd 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. # This code is based on work by Joshua Moelans
  2. # https://github.com/JoshuaMoelans/Master-Thesis-Godot-exploration (accessed March 2025)
  3. # Originally developed for his master's thesis at the University of Antwerp
  4. extends CharacterBody2D
  5. class_name BehaviorAgent
  6. # Reference used to instantiate instance of Utils class. Similar to importing.
  7. # Can make use of the methods in Utils.gd by calling them on this instance.
  8. var utils: Utils = Utils.new()
  9. enum TeamName { ALLY , ENEMY }
  10. @export var team: TeamName = TeamName.ALLY
  11. @export var health: int = 100 : set = set_health, get = get_health
  12. @export var speed: int = 150
  13. @onready var vision: Node2D = $vision
  14. var current_direction: Vector2
  15. var map: Grid2D
  16. var agent_state: Dictionary = {}
  17. signal state_changed(new_state)
  18. signal finished(state)
  19. func _ready() -> void:
  20. pass
  21. func _physics_process(delta: float) -> void:
  22. pass
  23. func setup():
  24. build_empty_map()
  25. init_agent_state()
  26. func set_health(h:int) -> void:
  27. health = clamp(h,0,100)
  28. func get_health() -> int:
  29. return health
  30. func rotate_to(direction: Vector2):
  31. rotation = lerp_angle(rotation, direction.angle(), 0.8)
  32. func stop_agent() -> void:
  33. velocity.x = move_toward(velocity.x, 0, speed)
  34. velocity.y = move_toward(velocity.y, 0, speed)
  35. move_and_slide()
  36. func get_team() -> int:
  37. return team
  38. func get_agent_state() -> Dictionary:
  39. return agent_state
  40. func change_direction(direction: Vector2):
  41. var current_map_tile = map.global_to_tile(global_position)
  42. current_direction = direction
  43. func avoid_collision():
  44. stop_agent()
  45. var new_direction: Vector2
  46. new_direction = utils.rotate_vec_left(current_direction)
  47. change_direction(new_direction)
  48. func check_vision():
  49. pass
  50. func build_empty_map():
  51. var instance: GameInstance = get_parent()
  52. var dimensions: Dictionary = instance.get_map_dimensions()
  53. var size: Vector2 = dimensions["size"]
  54. var map_tile_size = dimensions["tile_size"]
  55. var map_origin = dimensions["instance_offset"]
  56. var tile_count_x: int = floori(size.x / map_tile_size)
  57. var tile_count_y: int = floori(size.y / map_tile_size)
  58. var map_size = Vector2i(tile_count_x, tile_count_y)
  59. map = Grid2D.new(map_size, map_tile_size, map_origin, global_position)
  60. func init_agent_state():
  61. agent_state["name"] = self.get_name()
  62. agent_state["map"] = self.map.stringify_grid2d()
  63. func update_agent_state():
  64. agent_state["map"] = self.map.stringify_grid2d()
  65. self.state_changed.emit(agent_state)