Goodmorning,
I am having issues creating a spawn system that relies on the distance of the last object spawned from the spawnpoint. I do not want to use a timer to determine when the next object is spawned but will revert to this if needed.
Spawner
The system currently in place works as follows.
1.) The spawner spawns and object.
2.) Once the object is spawn, it is then cached temporarily to track its distance from the spawner.
3.) Once the cached object has reached a distance of say 1 meter from the spawnpoint, the cached object is set to null and the spawner spawns another object. And the cycle repeats.
4.) After a target score is reached the system will rest for 3 seconds and the next wave of objects are spawned but with a slight increase in speed.
The Object
Each object currently has a script on it called GameCube which simply transforms the spawned object downward based on a set speed variable (1). On tap the object is destroyed and a point is awarded.
So far the system works as intended but there are 2 issues.
1.) Each object should maintain the same distance between each other regardless of the speed. But each time the speed is increased the gap between the spawned objects gets larger.
2.) If the object is tapped and destroyed before it reaches the required distance from the spawner, there is then no way to determine when to spawn the next object.
(This has been remedied by spawning the objects off screen, therefore when the player sees the objects they are already pass the required distance)
Here is a copy of the spawn code:
public Transform objectToSpawn;
public bool canSpawn;
public float DistanceFromSpawnPoint;
public float MaximumDistanceLimit = 1f;
public Transform lastObjectSpawned;
// Use this for initialization
void Start ()
{
canSpawn = true;
}
// Update is called once per frame
void FixedUpdate ()
{
Spawn();
}
public void Spawn()
{
if (canSpawn && DistanceFromSpawnPoint == 0)
{
var SpawnedObject = Instantiate(objectToSpawn, transform.position, Quaternion.identity);
lastObjectSpawned = SpawnedObject;
canSpawn = false;
}
if (lastObjectSpawned != null)
{
if (!canSpawn && DistanceFromSpawnPoint < MaximumDistanceLimit)
{
DistanceFromSpawnPoint = Vector2.Distance(this.transform.position, lastObjectSpawned.transform.position);
}
else if (!canSpawn && DistanceFromSpawnPoint > MaximumDistanceLimit)
{
lastObjectSpawned = null;
DistanceFromSpawnPoint = 0;
canSpawn = true;
}
}
else
{
canSpawn = true;
}
}
Object:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameCube : MonoBehaviour
{
[SerializeField]
public static float speed = -15.0f;
// Update is called once per frame
void Update()
{
transform.position += transform.up * speed * Time.deltaTime;
if (transform.position.y < -5.5f)
{
Destroy(this.gameObject);
}
}
public void OnMouseDown()
{
if(this.transform.gameObject.tag == "White Cube")
{
Destroy(this.gameObject);
}
}
public void ScoreEvent(int _score)
{
_score++;
}
}