如何将一个游戏对象移动到位置更新功能之外的特定时间 [英] How to move a game object to a position for a specific duration outside the update function

查看:192
本文介绍了如何将一个游戏对象移动到位置更新功能之外的特定时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从斯威夫特SpriteKit背景学习团结,其中移动精灵的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的答案是接近,但缺少了重要的功能和使用 WaitForSeconds的()移动游戏对象是不可接受的。您应该使用线性插值协程的组合 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

这篇关于如何将一个游戏对象移动到位置更新功能之外的特定时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆