Sprite disappearing when playing and fixed path finding for tower defense games
Basically I am trying to make my gameObjects follow a fixed path in my tower defense game:
My idea is that I can create an array of invisible waypoint that will be attached to a single gameobject which the units can follow:
This is my hierachy view: link text
These are my inspector views (3 images): link text
I have attached the "Pathing" script to the "Path 1" gameobject which includes all my waypoints:
public class Pathing : MonoBehaviour {
public Transform[] path;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public Transform[] getPath(){
return path;
}
}
I have attached the "PathFollower" script to my unit which will follow the waypoint:
public class Pathfollower : MonoBehaviour {
public int currentPoint=0;
public Transform[] path;
public Pathing other;
public float speed=50.0f;
// Use this for initialization
void Start () {
path=other.getPath();
}
// Update is called once per frame
void Update () {
Debug.Log(currentPoint);
float dist =Vector3.Distance (path[currentPoint].position, transform.position);
transform.position=Vector3.MoveTowards(transform.position,path[currentPoint].position,speed*Time.deltaTime);
if(dist==0f){
currentPoint++;
}
if(currentPoint>=path.Length){
Debug.Log("reset");
currentPoint=0;
}
}
}
However, when I play the scene, this happens: link text
Questions:
1) Why did my unit disappear halfway?
2) Are there any more efficient ways to implement fixed path finding?
Thanks for any help rendered.
The only thing I can think of that might be causing this is if your path points have a different z-value from the sprite, they might be behind the camera (or the camera's clipping plane), so the sprite stops being shown when it gets close enough point. If you're using sprites on a canvas, or some other 2D setup, using Vector2 for positioning will make sure that it only moves on the x/y plane.
For 2), effeciency isn't a problem here. I'd move the dist = Vector3.Distance... to after the transform.position = ... call, as you want to change the direction you're moving immediately after getting to your waypoint.
Your answer
Follow this Question
Related Questions
How to make an object follow a path when necessary but move forward when holding mouse button? 0 Answers
pathfinding Error or follow player 0 Answers
2d NPC pathing 0 Answers
2D GameObject floats away 0 Answers