问题
I am creating a script that spawns random sized cubes (later to replaced with low-poly buildings) that fly past the player on the x-axis to give the illusion of being on a moving train.
I have the buildings moving at a set speed, that is constant no matter the framerate using Time.deltaTime.
My script is written to wait enough time for the first spawned object to move out of the way, before spawning the next, and it works perfectly with a set size for the objects, but can't seem to keep up if I randomize the size of the object slightly each frame.
It looks like this:
public GameObject buildingPrefab;
public GameObject spawnPoint;
public float spawningRatio;
public float randomSize;
public float distanceBetween;
public float ranMin;
public float ranMax;
float nextBuilding;
float speed;
// Start is called before the first frame update
void Start()
{
ranMin = 10f;
ranMax = 15f;
distanceBetween = 5f;
randomSize = 1;
speed = buildingPrefab.GetComponent<ScrollingBuilding>().speed;
}
// Update is called once per frame
void Update()
{
if(Time.time > nextBuilding)
{
spawningRatio = ((randomSize / 2) + (buildingPrefab.transform.localScale.x / 2) + distanceBetween) / (speed);
nextBuilding = Time.time + spawningRatio;
buildingPrefab.transform.localScale = new Vector3(randomSize, randomSize, randomSize);
Instantiate(buildingPrefab, spawnPoint.transform.position, Quaternion.identity);
randomSize = Random.Range(ranMin, ranMax);
}
}
}
The problem I am having is that the distance between the buildings isn't always the same, most likely due to the framerate not being completely stable. I tried to put the function into FixedUpdate(), but it suddenly became a lot more intensive and unsmooth.
My question is how to solve the issue, and make the distance between the objects constant, regardless of framerate here.
Thanks.
来源:https://stackoverflow.com/questions/62038766/having-objects-spawn-with-random-size-within-set-range-with-equal-distance-bet