Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Linq;
- using Godot;
- public partial class Enemy_Controller : Area2D
- {
- private Player_Controller player;
- private TileMapLayer tileMap;
- private Vector2I tileSize = new(16, 16);
- [Export] private Line2D pathfindingLine;
- private AStarGrid2D pathfindingGrid;
- private Vector2[] pathToPlayer;
- public override void _Ready()
- {
- // References
- player = GetTree().GetFirstNodeInGroup("Player") as Player_Controller;
- tileMap = GetTree().GetFirstNodeInGroup("TileMap") as TileMapLayer;
- if (tileMap == null) return;
- // Signals
- player?.Connect("PlayerFinishedAction", new Callable(this, "OnPlayerActionFinished"));
- // Snap enemy to TileMap
- GlobalPosition = tileMap.MapToLocal(tileMap.LocalToMap(GlobalPosition));
- // Pathfinding Setup
- pathfindingGrid = new AStarGrid2D();
- pathfindingGrid.Offset = tileSize / 2;
- pathfindingGrid.Region = tileMap.GetUsedRect();
- pathfindingGrid.CellSize = Vector2.One * tileSize;
- pathfindingGrid.DiagonalMode = AStarGrid2D.DiagonalModeEnum.Never;
- pathfindingGrid.Update();
- foreach (var cell in tileMap.GetUsedCells()) {
- pathfindingGrid.SetPointSolid(cell, tileMap.GetCellTileData(cell).GetCollisionPolygonsCount(0) > 0);
- }
- }
- private void OnPlayerActionFinished()
- {
- // Move toward player
- pathToPlayer = pathfindingGrid.GetPointPath((Vector2I)GlobalPosition / tileSize.X, (Vector2I)player.GlobalPosition / tileSize.Y);
- if (pathToPlayer.Length > 1)
- {
- pathToPlayer = pathToPlayer.Skip(1).ToArray();
- GlobalPosition = pathToPlayer[0];
- }
- pathfindingLine.Points = pathToPlayer;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment