CarloCupp CarloCupp - 24 days ago 7
C# Question

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

Answer

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