即使速度非常低,物体也可以立即移动到新位置 [英] Object moves instantly to new position even with very low speed

查看:147
本文介绍了即使速度非常低,物体也可以立即移动到新位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将对象从其原始位置缓慢移动到更高的位置,但是即使我使用诸如0.0001f这样的非常慢的速度,此代码也可以将对象立即移动到最高位置.我只在另一个代码中调用了LiftObj()1次,然后告诉它运行直到到达liftOffset为止.此代码有什么问题?

I want to move an object slowly from his original position to a little higher position but this code moves the object instantly to the highest position even when i use really slow speed like 0.0001f. I call LiftObj() inside another code 1 time only and i tell it run until it reaches the liftOffset. What is wrong with this code?

    void LiftObj(GameObject Obj) {

    float origianlPos = Obj.transform.position.y;
    while (Obj.transform.position.y < origianlPos + liftOffset) {
        Obj.transform.position += Vector3.up * 0.0001f;
        float newPos = Obj.transform.position.y;
        newPos = Mathf.Clamp (newPos, newPos, newPos + liftOffset);
        Obj.transform.position += Vector3.up * 0.0001f;
    }

推荐答案

但是此代码甚至可以将对象立即移动到最高位置 当我使用像0.0001f这样的非常慢的速度时.

but this code moves the object instantly to the highest position even when i use really slow speed like 0.0001f.

您根本不在等待.无论您的变量有多低,while循环都将尽可能快地执行.您应该在协程函数中执行此操作,然后等待yield关键字yield return null.

You are not waiting at-all. The while loop will execute as fast as possible no matter how low your variable is.You should be doing this in a coroutine function then wait with the yield keyword yield return null.

IEnumerator LiftObj(GameObject Obj)
{

    float origianlPos = Obj.transform.position.y;
    while (Obj.transform.position.y < origianlPos + liftOffset)
    {
        Obj.transform.position += Vector3.up * 0.0001f;
        float newPos = Obj.transform.position.y;
        newPos = Mathf.Clamp(newPos, newPos, newPos + liftOffset);
        Obj.transform.position += Vector3.up * 0.0001f;
        yield return null;
    }
    Debug.Log("Done Moving Up!");
}

然后将其移动:

StartCoroutine(LiftObj(myGameObject));

甚至不确定是否可以按预期工作,因为您缺少Time.delta,因此移动可能不平稳.如果您要做的只是从一个位置移到另一个加班,请使用下面的示例代码:

Not even sure that would work as expected because you are missing Time.delta so the movement may not be smooth. If all you want to do is move from one position to another overtime, use the sample code below:

IEnumerator LiftObj(GameObject playerToMove, Vector3 toPoint, float byTime)
{
    Vector3 fromPoint = playerToMove.transform.position;

    float counter = 0;

    while (counter < byTime)
    {
        counter += Time.deltaTime;
        playerToMove.transform.position = Vector3.Lerp(fromPoint, toPoint, counter / byTime);
        yield return null;
    }
}

4秒内从当前myGameObject位置移动到Vector3(0, 5, 0):

Move from current myGameObject position to Vector3(0, 5, 0) in 4 seconds:

StartCoroutine(LiftObj(myGameObject, new Vector3(0, 5, 0), 4));

这篇关于即使速度非常低,物体也可以立即移动到新位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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