TinyAdventure/objects/non_player_character.gd

69 lines
2.2 KiB
GDScript

class_name NonPlayerCharacter
extends CharacterBody3D
@export var reacts_to_player:bool = true :
set (value):
reacts_to_player = _set_reacts_to_player(value)
get:
return reacts_to_player
@onready var geometry: Node3D = null
@onready var player_detection: Area3D = %PlayerDetection
@onready var default_geometry: Node3D = %DefaultGeometry
@onready var animation_player: AnimationPlayer = %AnimationPlayer
const SPEED = 5.0
const JUMP_VELOCITY = 4.5
var tool_damage:bool = false
var tracking_node:Node3D = null
var _current_look_direction:Vector3 = Vector3.BACK
var _target_look_direction:Vector3 = Vector3.BACK
var _look_angle_damper:SpringDamper = SpringDamper.new(0, 2, 0.06, 0.003)
func _set_reacts_to_player(value:bool) -> bool:
if player_detection != null:
player_detection.monitoring = value
return value
func _ready() -> void:
player_detection.monitoring = reacts_to_player
geometry = find_child("Geometry")
if geometry == null:
geometry = default_geometry
else:
default_geometry.visible = false
animation_player.set_root("Geometry")
func _physics_process(delta: float) -> void:
_current_look_direction = basis.z
if tracking_node != null:
_target_look_direction = (tracking_node.global_position - global_position).normalized()
update_look_direction(delta)
func _on_player_detection_body_entered(body: Node3D) -> void:
if body is Player:
tracking_node = body
func _on_player_detection_body_exited(body: Node3D) -> void:
if body == tracking_node:
tracking_node = null
_target_look_direction = Vector3.BACK
func update_look_direction(delta:float) -> void:
var current_look_angle:float = _current_look_direction.signed_angle_to(Vector3.BACK, Vector3.UP)
var target_look_angle:float = _target_look_direction.signed_angle_to(Vector3.BACK, Vector3.UP)
if target_look_angle - current_look_angle > PI:
current_look_angle = current_look_angle + PI * 2
elif current_look_angle - target_look_angle > PI:
current_look_angle = current_look_angle - PI * 2
var damped_look_angle:float = _look_angle_damper.calc(current_look_angle, target_look_angle, delta)
_current_look_direction = Vector3(sin(-damped_look_angle), 0, cos(-damped_look_angle))
self.basis = Basis.looking_at(-_current_look_direction)