- Home /
Slowly move a GameObject on 1 axis, then destroy it.
Hi,
I want to make it so if a gameobject's x position is positive, I want it to slowly move until it's x position is 3, and then destroy itself (and the same for going right if the x position is negative), but no matter how much I try to understand what everyone has said it just moves instantly.
Here's what I have
//If the object is on the left, move left.
if (scoreValue.transform.position.x > 0)
{
while (scoreValue.transform.position.x < 3)
{
scoreValue.transform.Translate(Vector3.right * 1f, Space.World);
}
Destroy(scoreValue)
}
else
{
while (scoreValue.transform.position.x > -3)
{
scoreValue.transform.Translate(Vector3.left * 1f, Space.World);
}
Destroy(scoreValue)
}
Thanks!
Answer by JedBeryll · Jan 11, 2016 at 08:20 AM
It's inside the update function right? Don't use the "while" as that will be completely executed in 1 frame. Use time.deltaTime to move smoothly like this:
if(scoreValue.transform.position.x < 3)
{
scoreValue.transform.Translate(Vector3.right * time.deltaTime * speed, Space.World);
}
"speed" is a float. if you want slow try setting it to 1-3, or experiment with values.
Just to expand on this, the Update() function is called once per iteration of the main game loop and any changes made are rendered to the screen later in the loop. This means that, in order to see the movement on screen, it has to take place over multiple calls to Update().
By putting your movement code into a while loop, you've created a nested loop. The while loop will complete every time the Update() method runs, so your objects will always appear to move immediately every frame.
Sorry, I forgot to say. It's inside a void. Very new to this... first real try at making something.
I'll see if what you said still works. Thanks a lot.
Okay it's still doing the same thing! I'm guessing it's because it's in a void ins$$anonymous$$d of update? I'm really stumped with this one.
Okay, apparently Translate inside a void does nothing? $$anonymous$$aybe I'm just doing it wrong (quite likely). If I remove the Destroy part the object just sits there. It wasn't moving quickly, it was just killing itself.
I moved it into update and took away Destroy and now it works perfectly. Thank you!
//Destroy the value that was chosen
float speed = 3f;
//If the object is on the left, move left.
if (scoreValue != null && scoreValue.transform.position.x > 0)
{
if(scoreValue.transform.position.x < 3)
{
scoreValue.transform.Translate(Vector3.right * Time.deltaTime * speed, Space.World);
}
else
{
Destroy(scoreValue);
}
}
else if (scoreValue != null && scoreValue.transform.position.x < 0)
{
if(scoreValue.transform.position.x > -3)
{
scoreValue.transform.Translate(Vector3.left * Time.deltaTime * speed, Space.World);
}
else
{
Destroy(scoreValue);
}
}
If the void is in the Update, that's indeed the same thing ! If you're holding chocolate in your hand it doesn't matter that there's paper around it, you're holding the chocolate ^^