TinyAdventure/objects/non_player_character.gd

69 lines
2.2 KiB
GDScript
Raw Permalink Normal View History

2024-10-15 21:32:01 +02:00
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
2024-10-15 21:32:01 +02:00
@onready var player_detection: Area3D = %PlayerDetection
@onready var default_geometry: Node3D = %DefaultGeometry
@onready var animation_player: AnimationPlayer = %AnimationPlayer
2024-10-15 21:32:01 +02:00
const SPEED = 5.0
const JUMP_VELOCITY = 4.5
2024-11-01 18:07:23 +01:00
var tool_damage:bool = false
2024-10-15 21:32:01 +02:00
var tracking_node:Node3D = null
2024-11-15 11:35:37 +01:00
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)
2024-10-15 21:32:01 +02:00
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")
2024-10-15 21:32:01 +02:00
func _physics_process(delta: float) -> void:
2024-11-15 11:35:37 +01:00
_current_look_direction = basis.z
2024-10-15 21:32:01 +02:00
if tracking_node != null:
2024-11-15 11:35:37 +01:00
_target_look_direction = (tracking_node.global_position - global_position).normalized()
2024-10-15 21:32:01 +02:00
2024-11-15 11:35:37 +01:00
update_look_direction(delta)
2024-10-15 21:32:01 +02:00
func _on_player_detection_body_entered(body: Node3D) -> void:
2024-11-15 11:35:37 +01:00
if body is Player:
tracking_node = body
2024-10-15 21:32:01 +02:00
func _on_player_detection_body_exited(body: Node3D) -> void:
if body == tracking_node:
tracking_node = null
2024-11-15 11:35:37 +01:00
_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)