diff options
author | Lucas Fryzek <lucas.fryzek@fryzekconcepts.com> | 2024-09-22 15:33:22 +0100 |
---|---|---|
committer | Lucas Fryzek <lucas.fryzek@fryzekconcepts.com> | 2024-09-22 15:33:22 +0100 |
commit | e9b2e264f767da4e630a515ae3217f3966be9ce6 (patch) | |
tree | 3f7517104ed7061eb9be9e9d70b9abefa10cac80 /scripts/enemy.gd | |
parent | 5f6ba92130f55ec81f2336d488743c6ff2aeaf74 (diff) |
bsp_level_generator: Create navigation mesh
Also make enemy AI use nav mesh for finding player
Diffstat (limited to 'scripts/enemy.gd')
-rw-r--r-- | scripts/enemy.gd | 48 |
1 files changed, 44 insertions, 4 deletions
diff --git a/scripts/enemy.gd b/scripts/enemy.gd index 569905f..6be60c7 100644 --- a/scripts/enemy.gd +++ b/scripts/enemy.gd @@ -6,7 +6,12 @@ extends CharacterBody3D @export var target: Node3D ## Whether to use gravity on enemy -@export var gravity_enabled: bool = false +@export var gravity_enabled: bool = true + +## Use nav mesh or dumb path finding +@export var use_nav_mesh: bool = true + +@onready var nav_agent: NavigationAgent3D = $NavigationAgent3D var has_astar: bool = false var astar: AStar3D @@ -15,9 +20,17 @@ var gravity : float = ProjectSettings.get_setting("physics/3d/default_gravity") var original_color: Color +var mesh_ready = false + func _ready() -> void: if gravity_enabled: motion_mode = MotionMode.MOTION_MODE_GROUNDED + + NavigationServer3D.connect("map_changed", map_changed) + +func map_changed(_rid): + print("Map changed") + mesh_ready = true func chase_target(delta: float) -> void: var target_pos = target.position @@ -34,19 +47,46 @@ func chase_target(delta: float) -> void: velocity.y -= gravity * delta move_and_slide() + +func update_target_location(target_location: Vector3): + nav_agent.target_position = target_location + +func chase_nav_mesh(delta: float): + if not mesh_ready: + return + + if target != null: + update_target_location(target.global_position) + + var current_location = global_transform.origin + var next_location = nav_agent.get_next_path_position() + var new_velocity = (next_location - current_location).normalized() * speed + + # We only want to navigate on XZ plane + new_velocity.y = 0 + + velocity = new_velocity + + if not is_on_floor() and gravity_enabled: + velocity.y -= gravity * delta + move_and_slide() func _physics_process(delta: float) -> void: if target == null: return + if Input.is_action_pressed("ui_right"): + return + + if use_nav_mesh: + chase_nav_mesh(delta) + return + if not has_astar: # Just try to chase player directly chase_target(delta) return - if Input.is_action_pressed("ui_right"): - return - var target_pos = target.position var closest_me = astar.get_closest_point(position) var closest_target = astar.get_closest_point(target_pos) |