Hey guys!
So I'm trying to make a tower defense game in Unity using C#, and I need to know, how can I make a gameObject follow a path? You know, so I can make the enemies follow the road through the towers. Thank you!
Hey guys!
So I'm trying to make a tower defense game in Unity using C#, and I need to know, how can I make a gameObject follow a path? You know, so I can make the enemies follow the road through the towers. Thank you!
I'm working on a tower defence too and have come up with a few methods (I don't use unity or any game engines of the sort so idk if there's a better method for unity).
If your game is layed out as a grid then you could simply store coordinates of each tile of "path" that the enemy has to pass through, then have a very simple logical algo for the enemy pathfinding that checks each cardinal direction (left, right, up, down) for path except for the direction it previously travelled so it won't backtrack.
The one i used for an old version of my game is:
if (position.X % 64 == 0) //if the enemy is exactly whole on a single tile and not partially on another tile, where 64 = tile size
{
Rectangle rightCheck = new Rectangle((int)position.X + 64, (int)position.Y, (int)collision.X, ((int)collision.Y));
foreach (Pathway paths in pathwayObjects)
{
if (rightCheck.Intersects(paths.collision) && previousDirection != "left") //if there's pathway to the right plus if it didn't go left last time to avoid endless backtracking
{
velocity = new Vector2(1, 0); //I want to go right now
previousDirection = "right"; //I previously went right, so don't go left next time
break; //I've found a path, so stop checking paths until next update call
}
//repeat this same code for left, up and down directions
else { velocity = new Vector2(0, 0); } //error can't find path
}
}
Of course though you'd have to make sure that whatever velocity you set the game object to travel at is a factor of your tile size (64 in this case)
class EnemyPath : MonoBehavior
{
// create a list of transforms, each represent a point in the path. You can create empty game objects
// in your scene then add them to this array to create the waypoints in your path
public Transform[] path;
}
If you want to make the path a prefab, you can simply make all of the waypoints children of the EnemyPath object
class EnemyPath : MonoBehavior
{
public Transform[] path;
public void OnDrawGizmos()
{
Gizmos.color = Color.green;
for (int i = 1; path != null && i < path.Length; ++i)
{
Gizmos.DrawLine(path[i - 1].position, path[i].position);
}
}
}
To follow a path you have two options. You write your AI to be able to move towards a point. You follow a path by having the enemy goto the first point in the path, once it gets within a certain radius it moves to the next point.
enemy.transform.position = enemyPath.getPointAtDistance(enemy.distance);
enemy.distance += enemy.speed * Time.deltaTime;