Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Basic path finding in godot 3.1 using C# & Navigation2D node
using System.Linq;
using Godot;
using Godot.Collections;
namespace Gamma.Core.Scripts
{
public class Arena : Node2D
{
private int Speed = 300;
private bool moveNode = false;
private Navigation2D _navigation2D;
private Vector2[] _paths = new Vector2[]{};
private Node2D _char;
public override void _Ready()
{
_char = GetNode<Node2D>("Enemy");
_navigation2D = GetNode<Navigation2D>("Navigation2D");
}
public override void _Input(InputEvent @event)
{
if(Input.IsMouseButtonPressed((int) ButtonList.Left))
{
moveNode = true;
UpdateNavigationPath(_char.Position, GetLocalMousePosition());
}
}
public override void _Process(float delta)
{
if(moveNode)
{
MoveCharacter(Speed * delta);
}
}
private void UpdateNavigationPath(Vector2 start, Vector2 end)
{
_paths = _navigation2D.GetSimplePath(start, end);
_paths = _paths.Skip(1).Take(_paths.Length - 1).ToArray();
}
private void MoveCharacter(float speed)
{
var lastPosition = _char.Position;
for(var x = 0; x < _paths.Length; x++)
{
var distanceBetweenPoints = lastPosition.DistanceTo(_paths[x]);
if(speed <= distanceBetweenPoints)
{
_char.Position = lastPosition.LinearInterpolate(_paths[x], speed / distanceBetweenPoints);
break;
}
if (speed < 0.0)
{
_char.Position = _paths[0];
moveNode = false;
break;
}
speed -= distanceBetweenPoints;
lastPosition = _paths[x];
_paths = _paths.Skip(1).Take(_paths.Length - 1).ToArray();
}
}
}
}
@hodgej

This comment has been minimized.

Copy link

@hodgej hodgej commented Apr 27, 2019

Is this C#?

@exts

This comment has been minimized.

Copy link
Owner Author

@exts exts commented Apr 28, 2019

Yes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment