Godot-RTS-Concept/Navdrone.gd

96 lines
2.5 KiB
GDScript

extends CharacterBody3D
@export var speed = 2
@export var accel = 2
@onready var nav: NavigationAgent3D = $NavigationAgent3D
@export var cam: Camera3D
@export var navres: NavigationRegion3D
@export var block: PackedScene
var canMove
var current = 0
var path: PackedVector3Array
signal redid_navmesh
var destroy: Array
var rayOrigin= Vector3()
var rayEnd= Vector3()
var pathDone = true
func _ready():
canMove = false
destroy = Array()
print("new drone!")
func _physics_process(delta):
var direction = Vector3()
#if Input.is_action_just_pressed("left_click"):
# _do_path(_click_intersect())
if Time.get_ticks_msec()> 20 && current < (path.size()-1) && canMove:
var next = path[current+1]
look_at(Vector3(next.x,global_position.y,next.z))
direction = next - global_position
direction = direction.normalized()
velocity = velocity.lerp(direction*speed, accel * delta);
if self.position.distance_to(next)<nav.path_desired_distance:
current=current+1
elif current == path.size()-1 && !pathDone:
velocity = velocity*0
cleanUp()
pathDone = true
await get_tree().create_timer(0.05).timeout
#navres.bake_navigation_mesh()
move_and_slide()
func _do_path(goal:Vector3):
_coverPath(goal)
navres.bake_navigation_mesh()
current = 0
pathDone = false
func _click_intersect():
cleanUp()
var space_state = get_world_3d().direct_space_state
var mouse_position = get_viewport().get_mouse_position()
rayOrigin = cam.project_ray_origin(mouse_position)
rayEnd = rayOrigin + cam.project_ray_normal(mouse_position)*2000
var query = PhysicsRayQueryParameters3D.create(rayOrigin,rayEnd)
var intersection = space_state.intersect_ray(query)
if intersection.is_empty():
intersection = get_global_position()
print("nothing found")
#else:
#print (get_name())
return intersection.position
func _coverPath(Target:Vector3): #generates navmesh obstacles where drone is going
path = NavigationServer3D.map_get_path(get_world_3d().get_navigation_map(),global_position,Target,true)
#for point in path:
# var barrier = block.instantiate()
# navres.add_child(barrier)
# barrier.position=point
# destroy.append(barrier)
for n in (path.size()-1):
var barrier = block.instantiate()
navres.add_child(barrier)
barrier.position=(path[n+1]-path[n])/2+path[n]
barrier.scale=Vector3(barrier.scale.x,1,(path[n+1]-path[n]).length())
barrier.look_at(path[n+1])
destroy.append(barrier)
func cleanUp(): ##cleans navmesh obstacles
for d in destroy:
d.queue_free()
destroy.clear()
#func _on_navigation_agent_3d_navigation_finished():
#cleanUp()