为什么动画之间似乎比声明的时间更长,并防止延迟的Destroy()

本文关键字:延迟 Destroy 之间 动画 时间 声明 为什么 | 更新日期: 2023-09-27 18:06:54

我有这样的代码:

void OnCollisionEnter (Collision collision)
{
    if (canCollide == true) {
        canCollide = false;
        ContactPoint contactPoint = collision.contacts [0];
        GameObject cube = GameObject.CreatePrimitive (PrimitiveType.Cube);
        cube.transform.localScale = new Vector3 (5, 5, 5);
        cube.transform.position = contactPoint.point;
        iTween.MoveTo (cube, iTween.Hash (
            "y", 40, 
            "time", 0.5));
        iTween.MoveTo (cube, iTween.Hash (
            "position", new Vector3 (55, 79, 10), 
            "time", 0.5f,
            "delay", 0.5f,
            "oncompletetarget", GameObject.Find ("PlayerCar"), 
            "oncomplete", "IncrementGauge"));
        Destroy (cube, 1.1f);
    }
}

这工作正常,两个动画是顺序的。但是时间的总和应该是1秒。但是Destroy()不能延迟1秒,它必须至少延迟1.1秒。为什么?我能以某种方式更快地摧毁立方体,并且仍然有IncrementGauge()触发(1秒摧毁,防止触发IncrementGauge())。

谢谢。

为什么动画之间似乎比声明的时间更长,并防止延迟的Destroy()

这是因为iTween库在每次Update调用中检查1.0秒是否已经过去,这不可能是1.0秒,因为它取决于你的帧率和浮点运算是不精确的。

你的问题可以通过销毁立方体并在相同的回调方法DestroyCubeAndIncrementGauge()中增加测量值来解决,该方法作为字符串传递给参数oncomplete

public class CollisionObject : MonoBehaviour 
{
    [SerializeField]
    private bool canCollide = true;
    void OnCollisionEnter(Collision collision)
    {
        if (canCollide == true) {
            canCollide = false;
            ContactPoint contactPoint = collision.contacts [0];
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.localScale = new Vector3(5, 5, 5);
            cube.transform.position = contactPoint.point;
            iTween.MoveTo(cube, iTween.Hash(
                "y", 40, 
                "time", 0.5));
            iTween.MoveTo(cube, iTween.Hash(
                "position", new Vector3 (55, 79, 10), 
                "time", 0.5f,
                "delay", 0.5f,
                "oncompletetarget", this.gameObject, 
                "oncompleteparams", cube,
                "oncomplete", "DestroyCubeAndIncrementGauge"
            ));
        }
    }
    public void DestroyCubeAndIncrementGauge(GameObject cube)
    {
        // destroy the cube
        Destroy(cube);
        // inform the PlayerCar to IncrementGauge
        GameObject.Find("PlayerCar").SendMessage("IncrementGauge");
    }
}