Having objects spawn, with random size within set range, with equal distance between them regardless of framerate

筅森魡賤 提交于 2020-05-31 04:47:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!