随着时间的推移移动游戏对象
Q:
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:
我正在从Swift Spritekit背景中学习团结,其中移动Sprite的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)
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.
我想知道在特定持续时间内将精灵转移到特定位置的等效或类似方法(例如第二个),其延迟不必在更新功能中调用。
A:
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.
GJTTT1的答案很接近,但缺少重要功能,并且使用WaitForSeconds()
用于移动游戏对象是不可接受的。您应该使用Lerp
, Coroutine
和Time.deltaTime
的组合。您必须理解这些东西,才能能够从脚本统一制作动画。
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;
}
本站发布的内容若无意中侵犯到您的权益,请联系我们,本站将在一个工作日内删除。

912sy » 随着时间的推移移动游戏对象