小编典典

随着时间的推移移动GameObject

c#

我正在从Swift SpriteKit背景中学到Unity,在该背景下,移动精灵的x位置与运行以下动作一样简单:

let moveLeft = SKAction.moveToX(self.frame.width/5, duration: 1.0)
let delayAction = SKAction.waitForDuration(1.0)
let handSequence = SKAction.sequence([delayAction, moveLeft])
sprite.runAction(handSequence)

我想知道一种在相同的持续时间(例如一秒钟)内将精灵移动到特定位置的等效或类似方法,而不必在更新函数中调用它。


阅读 258

收藏
2020-05-19

共1个答案

小编典典

gjttt1的答案很接近,但是缺少重要的功能,并且不能使用WaitForSeconds()来移动 GameObject
。您应该使用的组合LerpCoroutineTime.deltaTime。您必须了解这些内容,才能从Unity中的脚本制作动画。

public GameObject objectectA;
public GameObject objectectB;

void Start()
{
    StartCoroutine(moveToX(objectectA.transform, objectectB.transform.position, 1.0f));
}


bool isMoving = false;

IEnumerator moveToX(Transform fromPosition, Vector3 toPosition, float duration)
{
    //Make sure there is only one instance of this function running
    if (isMoving)
    {
        yield break; ///exit if this is still running
    }
    isMoving = true;

    float counter = 0;

    //Get the current position of the object to be moved
    Vector3 startPos = fromPosition.position;

    while (counter < duration)
    {
        counter += Time.deltaTime;
        fromPosition.position = Vector3.Lerp(startPos, toPosition, counter / duration);
        yield return null;
    }

    isMoving = false;
}

类似的问题:SKAction.scaleXTo

2020-05-19