using Godot;
public partial class Nav : CharacterBody2D
{
public float movement_speed = 300.0f;
public Vector2 movement_target_position = new Vector2(950, 500);
public NavigationAgent2D navigation_agent;
public override void _Ready()
{
navigation_agent = GetNode<NavigationAgent2D>("NavigationAgent2D");
// These values need to be adjusted for the actor's speed
// and the navigation layout.
navigation_agent.PathDesiredDistance = 4.0f;
navigation_agent.TargetDesiredDistance = 4.0f;
// Make sure to not await during _ready.
CallDeferred("actor_setup");
// Calls the method on the object during idle time. Always returns null,
// not the method's result.
}
public async void actor_setup()
{
// Wait for the first physics frame so the NavigationServer can sync.
// On the first frame the NavigationServer map has not synchronized region
// data and any path query will return empty. Await one frame to pause
// scripts until the NavigationServer had time to sync.
//await ToSignal(GetTree(), "physics_frame");
await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame);
// physics_frame
// Emitted immediately before Node._physics_process is called on every node
// in the SceneTree.
// Now that the navigation map is no longer empty, set the movement target.
set_movement_target(movement_target_position);
}
public void set_movement_target(Vector2 movement_target)
{
navigation_agent.TargetPosition = movement_target;
}
public override void _PhysicsProcess(double delta)
{
if (navigation_agent.IsNavigationFinished())
{
return;
}
//Vector2 current_agent_position = GlobalPosition;
//Vector2 next_path_position = navigation_agent.GetNextPathPosition();
//Vector2 new_velocity = next_path_position - current_agent_position;
Vector2 new_velocity = ToLocal(navigation_agent.GetNextPathPosition());
new_velocity = new_velocity.Normalized();
new_velocity = new_velocity * movement_speed;
Velocity = new_velocity;
MoveAndSlide();
}
}