随着时间的推移移动GameObject [英] 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)
我想知道一种将Sprite移到特定位置特定时间(例如一秒钟)的等效方法,该方法不需要在更新函数中调用.
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的答案很接近,但是缺少重要的功能,并且不能使用WaitForSeconds()
来移动 GameObject .您应该结合使用Lerp
,Coroutine
和Time.deltaTime
.您必须了解这些内容,才能从Unity中的脚本制作动画.
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
这篇关于随着时间的推移移动GameObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!