Created
April 27, 2019 07:00
-
-
Save exts/f303c8cb9751bc25f8f9cb17a0006c2b to your computer and use it in GitHub Desktop.
Basic path finding in godot 3.1 using C# & Navigation2D node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is this C#?