随着时间的推移移动GameObject

Nul*_*ess 8 c# unity-game-engine unity5

我正在从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)
Run Code Online (Sandbox Code Playgroud)

我想知道一种等效或类似的方法,将精灵移动到特定持续时间(例如,一秒)的特定位置,并且延迟不必在更新函数中调用.

Pro*_*mer 19

gjttt1的答案很接近,但缺少重要的功能,WaitForSeconds()用于移动GameObject是不可接受的.您应该使用的组合Lerp,CoroutineTime.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;
}
Run Code Online (Sandbox Code Playgroud)

类似的问题:SKAction.scaleXTo