godot-steering-ai-framework/project/src/Behaviors/GSTFollowPath.gd

51 lines
1.6 KiB
GDScript3
Raw Normal View History

# Produces a linear acceleration that moves the agent along the specified path.
2020-01-09 18:26:35 +01:00
class_name GSTFollowPath
2020-01-16 23:14:50 +01:00
extends GSTArrive
2020-01-09 18:26:35 +01:00
2020-01-27 19:24:05 +01:00
# The path to follow and travel along
2020-01-09 18:26:35 +01:00
var path: GSTPath
2020-01-27 19:24:05 +01:00
# The distance along the path to generate the next target position.
var path_offset := 0.0
2020-01-09 18:26:35 +01:00
2020-01-27 19:24:05 +01:00
# Whether to use `GSTArrive` behavior on an open path.
var arrive_enabled := true
2020-01-27 19:24:05 +01:00
# The amount of time in the future to predict the owning agent's position along the path. Setting
# it to 0 will force non-predictive path following.
var prediction_time := 0.0
2020-01-09 18:26:35 +01:00
func _init(
agent: GSTSteeringAgent,
path: GSTPath,
path_offset := 0.0,
prediction_time := 0.0).(agent, null) -> void:
2020-01-09 18:26:35 +01:00
self.path = path
self.path_offset = path_offset
self.prediction_time = prediction_time
func _calculate_steering(acceleration: GSTTargetAcceleration) -> GSTTargetAcceleration:
var location := (
2020-01-09 18:26:35 +01:00
agent.position if prediction_time == 0
else agent.position + (agent.linear_velocity * prediction_time))
var distance := path.calculate_distance(location)
var target_distance := distance + path_offset
2020-01-09 18:26:35 +01:00
var target_position := path.calculate_target_position(target_distance)
2020-01-09 18:26:35 +01:00
2020-01-15 20:42:24 +01:00
if arrive_enabled and path.open:
2020-01-09 18:26:35 +01:00
if path_offset >= 0:
if target_distance > path.length - deceleration_radius:
return _arrive(acceleration, target_position)
else:
if target_distance < deceleration_radius:
return _arrive(acceleration, target_position)
acceleration.linear = (target_position - agent.position).normalized()
acceleration.linear *= agent.linear_acceleration_max
2020-01-09 18:26:35 +01:00
acceleration.angular = 0
return acceleration