Guest User

wawa

a guest
Aug 28th, 2025
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 KB | None | 0 0
  1. using System.Linq;
  2. using Godot;
  3.  
  4. public partial class Enemy_Controller : Area2D
  5. {
  6.     private Player_Controller player;
  7.     private TileMapLayer tileMap;
  8.     private Vector2I tileSize = new(16, 16);
  9.    
  10.     [Export] private Line2D pathfindingLine;
  11.     private AStarGrid2D pathfindingGrid;
  12.     private Vector2[] pathToPlayer;
  13.    
  14.     public override void _Ready()
  15.     {
  16.         // References
  17.         player = GetTree().GetFirstNodeInGroup("Player") as Player_Controller;
  18.         tileMap = GetTree().GetFirstNodeInGroup("TileMap") as TileMapLayer;
  19.         if (tileMap == null) return;
  20.        
  21.         // Signals
  22.         player?.Connect("PlayerFinishedAction", new Callable(this, "OnPlayerActionFinished"));
  23.  
  24.         // Snap enemy to TileMap
  25.         GlobalPosition = tileMap.MapToLocal(tileMap.LocalToMap(GlobalPosition));
  26.        
  27.         // Pathfinding Setup
  28.         pathfindingGrid = new AStarGrid2D();
  29.         pathfindingGrid.Offset = tileSize / 2;
  30.         pathfindingGrid.Region = tileMap.GetUsedRect();
  31.         pathfindingGrid.CellSize = Vector2.One * tileSize;
  32.         pathfindingGrid.DiagonalMode = AStarGrid2D.DiagonalModeEnum.Never;
  33.         pathfindingGrid.Update();
  34.  
  35.         foreach (var cell in tileMap.GetUsedCells()) {
  36.             pathfindingGrid.SetPointSolid(cell, tileMap.GetCellTileData(cell).GetCollisionPolygonsCount(0) > 0);
  37.         }
  38.     }
  39.  
  40.     private void OnPlayerActionFinished()
  41.     {
  42.         // Move toward player
  43.         pathToPlayer = pathfindingGrid.GetPointPath((Vector2I)GlobalPosition / tileSize.X, (Vector2I)player.GlobalPosition / tileSize.Y);
  44.         if (pathToPlayer.Length > 1)
  45.         {
  46.             pathToPlayer = pathToPlayer.Skip(1).ToArray();
  47.             GlobalPosition = pathToPlayer[0];
  48.         }
  49.         pathfindingLine.Points = pathToPlayer;
  50.     }
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment