40 lines
996 B
GDScript
40 lines
996 B
GDScript
extends CharacterBody2D
|
|
|
|
@export var speed: float = 60.0
|
|
@export var attack_distance: float = 32.0
|
|
@export var think_time: float = 0.2
|
|
|
|
var _target: Player = null
|
|
var _time_thought: float = 0.0
|
|
|
|
|
|
func _physics_process(delta: float) -> void:
|
|
_time_thought += delta
|
|
if _time_thought >= think_time:
|
|
_time_thought -= think_time
|
|
if _target:
|
|
var x_difference: float = _target.position.x - position.x
|
|
var distance: float = abs(x_difference)
|
|
if abs(distance - attack_distance) > speed * think_time:
|
|
var is_too_far_sgn: float = sign(distance - attack_distance)
|
|
velocity.x = sign(x_difference) * is_too_far_sgn * speed
|
|
else:
|
|
velocity.x = 0
|
|
$AnimatedSprite2D.flip_h = x_difference < 0
|
|
else:
|
|
velocity.x = 0
|
|
|
|
if not is_on_floor():
|
|
velocity += get_gravity() * delta
|
|
|
|
move_and_slide()
|
|
|
|
|
|
func _on_detection_body_entered(body: Node2D) -> void:
|
|
if body is Player:
|
|
_target = body
|
|
|
|
|
|
func _on_chase_body_exited(body: Node2D) -> void:
|
|
if body == _target:
|
|
_target = null
|