Hi,
I created a game where ghosts are following the player. There are certain points where these ghosts are spawned. But, after a few seconds, they get into each other or combine with each other because there is only one path that follows the player. I thought preventing them to do that would solve the problem, so I thought of adding colliders, but that would also make them collide with other objects, which I don’t want. What should I do?
Here is my code:
For the Ghosts:
public class Ghost : MonoBehaviour
{
public float speed;
public float StoppingDistance;
public float RetreatDistance;
public float idleDistance;
private Transform TargetPlayer;
private float TimebetweenShots;
public float StartTimebetweenShots;
public GameObject Projectile;
// Start is called before the first frame update
void Start()
{
TargetPlayer = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
TimebetweenShots = StartTimebetweenShots;
}
// Update is called once per frame
void Update()
{
if (transform.position.x > TargetPlayer.position.x)
{
transform.eulerAngles = new Vector3(0, 180, 0);
}
if (transform.position.x < TargetPlayer.position.x)
{
transform.eulerAngles = new Vector3(0, 0, 0);
}
if (Vector2.Distance(transform.position, TargetPlayer.position) > StoppingDistance)
{
transform.position = Vector2.MoveTowards(transform.position, TargetPlayer.position, speed * Time.deltaTime);
} else if (Vector2.Distance(transform.position, TargetPlayer.position) < StoppingDistance && Vector2.Distance(transform.position, TargetPlayer.position) > RetreatDistance)
{
transform.position = this.transform.position;
} else if (Vector2.Distance(transform.position, TargetPlayer.position) < RetreatDistance)
{
transform.position = Vector2.MoveTowards(transform.position, TargetPlayer.position, -speed * Time.deltaTime);
}
if (TimebetweenShots <= 0)
{
Instantiate(Projectile, transform.position, transform.rotation);
TimebetweenShots = StartTimebetweenShots;
}
else
{
TimebetweenShots -= Time.deltaTime;
}
}
}
And this is the code for spawning if anyone needs it:
–
–
public class GhostSpawner : MonoBehaviour
{
public float startTimeBetweenSpawns;
private float TimebetweenSpawns;
public float SpawnDistance;
public GameObject Ghosts;
// Start is called before the first frame update
void Start()
{
TimebetweenSpawns = startTimeBetweenSpawns;
Instantiate(Ghosts, transform.position, transform.rotation);
}
// Update is called once per frame
void Update()
{
if (Vector2.Distance(GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>().transform.position, gameObject.transform.position) <= SpawnDistance)
{
if (TimebetweenSpawns <= 0)
{
Instantiate(Ghosts, transform.position, transform.rotation);
TimebetweenSpawns = startTimeBetweenSpawns;
}
else
{
TimebetweenSpawns -= Time.deltaTime;
}
}
}
}
Also,
here is a screenshot from my gameplay.
Here there are actually three ghosts.