随着时间的推移移动游戏对象 [英] Move GameObject over time
问题描述
我正在从 Swift SpriteKit 背景中学习 Unity,其中移动 sprite 的 x 位置与运行动作一样直接,如下所示:
I am learning Unity from a Swift SpriteKit background where moving a sprite's x Position is as straight forward as an running an action as below:
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)
我想知道在特定持续时间(例如,一秒)内将精灵移动到特定位置的等效或类似方法,并且延迟不必在更新函数中调用.
I would like to know an equivalent or similar way of moving a sprite to a specific position for a specific duration (say, a second) with a delay that doesn't have to be called in the update function.
推荐答案
gjttt1's answer is close 但缺少重要功能和使用 WaitForSeconds()
移动 GameObject是不可接受的.您应该结合使用 Lerp
、Coroutine
和 Time.deltaTime
.您必须了解这些内容才能在 Unity 中通过 Script 制作动画.
gjttt1's answer is close but is missing important functions and the use of WaitForSeconds()
for moving GameObject is unacceptable. You should use combination of Lerp
, Coroutine
and Time.deltaTime
. You must understand these stuff to be able to do animation from Script in 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
这篇关于随着时间的推移移动游戏对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!