fix: patrol navigation now first targets the closest point on the path

This commit is contained in:
Sara 2025-07-21 15:50:26 +02:00
parent 9517588415
commit c05d3aa28f
4 changed files with 20 additions and 14 deletions

View file

@ -52,8 +52,8 @@ void WretchedPatrolState::enter_state() {
float const max_speed{ get_unit()->get_patrol_speed() };
get_target()->set_movement_speed(max_speed);
get_nav()->set_max_speed(max_speed);
this->path_point = this->path->get_closest_point(get_target()->get_global_position());
get_nav()->set_target_position(this->path->point_at(this->path_point));
Vector3 const nav_target{ this->path->get_closest_point(get_target()->get_global_position(), &this->path_point) };
get_nav()->set_target_position(nav_target);
}
void WretchedPatrolState::process(double delta) {

View file

@ -45,20 +45,26 @@ Vector3 PatrolPath::point_at_unchecked(int const index) const {
return this->path.get(index)->get_global_position();
}
int PatrolPath::get_closest_point(Vector3 global_position) {
Vector3 PatrolPath::get_closest_point(Vector3 global_position, int *idx) {
int best_choice_idx{ -1 };
float best_choice_distance{ Math::INF };
Vector3 point{ 0, 0, 0 };
for (int i{ 0 }; i < point_count(); ++i) {
int const next_idx{ (i + 1) % point_count() };
Vector3 const current{ point_at(i) };
Vector3 const next{ point_at_unchecked(next_idx) };
Vector3 const path_direction{ (next - current).normalized() };
Vector3 const direction{ (global_position - current).normalized() };
float const distance{ global_position.distance_squared_to(next) };
if (path_direction.dot(direction) > 1.0 && distance < best_choice_distance) {
best_choice_idx = next_idx;
Vector3 const difference{ global_position - current };
Vector3 const closest{ current + path_direction.dot(difference) * path_direction };
float const distance{ global_position.distance_squared_to(closest) };
if (distance < best_choice_distance) {
best_choice_idx = i;
best_choice_distance = distance;
point = closest;
}
}
return best_choice_idx;
if (idx) {
*idx = best_choice_idx;
}
return point;
}

View file

@ -17,7 +17,7 @@ public:
int point_count() const;
Vector3 point_at(int &index) const;
Vector3 point_at_unchecked(int const index) const;
int get_closest_point(Vector3 global_position);
Vector3 get_closest_point(Vector3 global_position, int *idx);
private:
Vector<Node3D *> path{};