user7151127
user7151127

Reputation:

Object moves instantly to new position even with very low speed

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;
    }

Upvotes: 0

Views: 293

Answers (2)

Programmer
Programmer

Reputation: 125455

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

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!");
}

then move it with:

StartCoroutine(LiftObj(myGameObject));

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;
    }
}

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

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

Upvotes: 1

Alex Wells
Alex Wells

Reputation: 105

You're using a while loop in an incorrect place here.

While loops continue to execute with in one frame as long as the statement is true. This means that regardless of how low your magnitude multiplier is (the 0.001f) it will just take more iterations with in the same frame to reach the target.

You should check to see each frame whether the object has reached its goal yet, and if it hasn't apply the transformation.

Upvotes: 0

Related Questions