- Home /
Why is transform.Translate not working?
So I have written this code:
void OnTriggerEnter (Collider other)
{
if(other.gameObject.CompareTag ("PickUp"))
{
Destroy(other.gameObject);
Vector3 roll = new Vector3(500.0f,0.0f,0.0f);
object2.transform.Translate(roll * Time.deltaTime);
}
}
When the player collides with the pick-up object, the pick-up object get destroyed and another gameObject (which I named object2) rolls to a new position. However, object2 is not changing its position the way I want it to. It just shifts to its new position. It does not roll to the new position. How to I make object2 (which is a sphere by the way) roll to its new position?
Answer by Eric5h5 · Apr 26, 2015 at 02:44 AM
OnTriggerEnter only runs once, as the name strongly implies (that is, when the trigger is entered). Since Time.deltaTime is likely to be a small number, Translate is working as it always does, but it won't move very far. If you want the object to move continuously over time, you'll have to program it to do that. Coroutines are a convenient way (and OnTriggerEnter can be a coroutine).
Just to add some detail here, if you intend on actual rolling of the sphere, not just movement, you need to put that in as well. You would need to do a rotate as well as the translate.
Another thing to consider, if you think it would fit your game, you could convert it to use the physics engine ins$$anonymous$$d of directly manipulating the transforms yourself. This does add overhead and complicates things in some ways, but if you need physics, it works great, and can make other parts of the game work right too.
Ok so I tried adding the script to object2 this time. Here's what I wrote:
if (GameObject.Find("Cube") == null)
{
Vector3 shift = new Vector3 (500.0f,0.0f,0.0f);
rigidbody.transform.Translate (shift * Time.deltaTime);
}
This almost solved my problem. object2 does roll this time but it just rolls off the plane and just keeps on rolling on empty space. It does not stop at a new position. I tried lowering the x value on Vector3 but that just slows the rolling speed. How do I fix this?
You have to make it stop at the new position. You will need to program it in somehow. $$anonymous$$aybe you can say if the distance to the new position you desire is a really small amount, then directly place it there, and stop the rolling.
Your answer
Follow this Question
Related Questions
Destroying Game Object On MouseButtonDown + Distance Collision 0 Answers
Multiple Cars not working 1 Answer
Search GameObjects while in game 3 Answers
Distribute terrain in zones 3 Answers
I need help with triggers 1 Answer