Search code examples
unity-game-enginepath-findingtile

Move Object around a platform of tiles in Unity


I want to make a spinning spike to move around a platform made out of tiles like in the following enter image description here

I have written every possible state on where to move when platform tiles block the spike's way. It would look something like this

     for (int i = 0; i < platformTileMap.Length; i++)
     {
         if (platformTileMap[i].HasTile(cellPosition + new Vector3Int(0, -1, 0))) // BOTTOM
         {
             moveX = moveDir;
         }
         else if (platformTileMap[i].HasTile(cellPosition + new Vector3Int(0, 1, 0))) // TOP
         {
             moveX = -moveDir;
         }
         else if (platformTileMap[i].HasTile(cellPosition + new Vector3Int(-1, -1, 0))) //BOT LEFT
         {
             if (moveDir == 1)
             {
                 moveY = -1;
             }
             else moveX = moveDir;
         }
         else if (platformTileMap[i].HasTile(cellPosition + new Vector3Int(1, 1, 0))) //TOP RIGHT
         {
             if (moveDir == 1)
             {
                 moveY = 1;
             }
             else moveX = -moveDir;
         }
         else if (platformTileMap[i].HasTile(cellPosition + new Vector3Int(1, -1, 0))) // BOT RIGHT
         {
             if (moveDir == 1)
             {
                 moveX = moveDir;
             }
             else
             {
                 moveY = -1;
             }
         }
         else if (platformTileMap[i].HasTile(cellPosition + new Vector3Int(-1, 1, 0))) // TOP LEFT
         {
             if (moveDir == -1)
             {
                 moveY = 1;
             }
             else
             {
                 moveX = -moveDir;
             }
         }

I feel like there has to be a more efficient way to solve this. Do I really have to write every possibility in if statements? Can I achieve this with pathfinding?


Solution

  • How about this

    1. Use raycast

    enter image description here

    1. Place Empty GameObject and rotate spike when it arrives them

    enter image description here