- Home /
How to move an object to a height
Hello,
I'm new to scripting and I need to make a object slowly move up and stop at 30 on the y axis. It must be done in C#
So far I have this:
while (transform.position.y < 30)
{
transform.Translate (Vector3.up * Time.deltaTime, Space.World);
}
But the object just starts in the air. Please help.
It appears that way. The thing is actually moving bit by bit but because its in a while loop you don't see the results updating, you only see the end result. Do it a bit per frame ins$$anonymous$$d to observe a movement ins$$anonymous$$d of a transform.Teleport.
That makes sense, how would I do that? What confuses me is without the loop it works fine, and slowly starts going up; but with the loop it starts in the air.
Answer by richyrich · Nov 19, 2014 at 05:56 PM
That makes sense, how would I do that? What confuses me is without the loop it works fine, and slowly starts going up; but with the loop it starts in the air.
Time.deltaTime is the time in seconds it took to complete the last frame (http://docs.unity3d.com/ScriptReference/Time-deltaTime.html).
The while loop keeps on using the same value over and over until the height is reached and only then allows other code to run that updates the graphics and allows you to see anything.
Let's suppose you ask me to use a pulley to lift a block. I can go to the pulley, start pulling and while the block is not high enough, I'll keep pulling. Once the block is at the right height, I report back and tell you the job is finished, I execute the update once - you have only seen the stone in two states - bottom (before you asked) and top.
Now let's assume I have no confidence in myself and am desperately afraid I might take the block too high. In this case I lift the block, tie it off and ask if it's high enough - I update you. You tell me no, it's not enough. So I return and pull a bit more. In this way, you see things slowly changing. That's the difference. In graphics, you don't see the change in the while because during the loop, there are no updates of the graphics, there is no pause.
In answer to your question, just replace the while with an if
if (transform.position.y < 30f)
{
transform.Translate (Vector3.up * Time.deltaTime, Space.World);
}