为什么lerp函数不适用于实例化的随机Gameobject?

时间:2019-09-05 13:49:00

标签: c# unity3d lerp

该代码有助于连续循环移动游戏对象。我也希望随机生成的多维数据集也遵循相同的模式。一轮结束时,我没有添加停止游戏对象生成的条件。当前,生成的游戏对象不会移动。

最终的想法是生成飞溅场景。我想知道以下方法是否也是gpu高效的!

A

1 个答案:

答案 0 :(得分:0)

实例化的游戏对象不移动的原因是因为您没有分配给它们的任何位置! splashImagesGOList[selection].transform.position预制件之一的位置。在当前代码中,您实例化对象,然后再从不与实例化对象进行交互。

您应该通过将运动逻辑分离到不同的脚本中并将该脚本附加到列表中的每个预制件上,使每个对象处理自己的运动。您可以使用Mathf.Repeat进行当前代码似乎要执行的循环操作。

现在,还不清楚您要通过重复同时随机实例化来实现哪种模式,但是无论如何,您可能并不打算将InvokeRepeating放在Update中。另外,您应该具有某种结束条件,以终止对PickPoints的重复CancelInvoke("PickPoints");调用。创建数量不断增加的对象并不是gpu高效的;)

总的来说,这些更改可能看起来像这样:

public class SpashImageMover : MonoBehaviour
{
    public Vector3 startPosition;
    public Vector3 endPosition;
    public float3 lerpTime;

    private float t = 0; // in case code in Start is removed

    void Start()
    {
        // remove these two lines if you don't want the objects synchronized
        t = Mathf.Repeat(Time.time/lerpTime, 1f);
        transform.position = Vector3.Lerp(startPosition, endPosition, t);
    }

    void Update()
    {
        t = Mathf.Repeat(t + Time.deltaTime / lerpTime, 1f);

        transform.position = Vector3.Lerp(startPosition, endPosition, t);
    }
}

public class IntegratedScrpt : MonoBehaviour
{
    public List<GameObject> splashImagesGOList;

    public float InvokeRate = 10f;

    private int selection;

    // Loop mode variables
    private Vector3 startPosition;
    private Vector3 endPosition;

    //for Vector Lerp
    private float lerpTime = 9f;

    // end condition for PickPoints
    private bool invokingPickPoints;
    private float pickPointsTimeRemaining = 27f;


    void Start()
    {
        startPosition = splashImagesGOList[1].transform.position;
        Debug.LogError("selection VALUE AT" + selection);

        endPosition = Vector3.back * distance;

        InvokeRepeating("PickPoints", 1.0f, InvokeRate);
        invokingPickPoints = true;
    }

    void Update()
    {
        if (invokingPickPoints) 
        {
            pickPointsTimeRemaining -= Time.deltaTime;
            if (pickPointsTimeRemaining <= 0 ) 
            {
                CancelInvoke("PickPoints");
                invokingPickPoints = false;
            }
        }
    }

    // code for instantiating the gameobjects
    void PickPoints()  
    {
        foreach (GameObject cube01 in splashImagesGOList)
        {
            int selection = UnityEngine.Random.Range(0, splashImagesGOList.Count);
            // Instantiate(splashImagesGOList[selection], cube01.transform.position, cube01.transform.rotation);
            GameObject newGO = Instantiate(splashImagesGOList[selection], startPosition, cube01.transform.rotation);

            SpashImageMover mover = newGO.GetComponent<SpashImageMover>();
            mover.startPosition = startPosition;
            mover.endPosition = endPosition;
            mover.lerpTime = lerpTime;
        }
    }
}

作为旁注,如果现在发现您不喜欢实例化对象的方式,则对于描述您要实现的目标的非常描述性的解释,这将更适合于其他问题。这个问题太广泛了,无法在这里解决。