- Home /
How do I move an object from point A to point B using a trigger?
I'm basically trying to move a box from one side of the room to the other when the player enters a trigger. It seems like such a simple task, but all the solutions I've found seem extremely complicated... I'm a complete newbie to coding in general, so I'm sorry if I'm a bit dumber than you guys are used to.
Answer by helloiam · Mar 24, 2013 at 11:01 AM
The trigger is easy that is what you have to find out for yourself
Answer by Kajos · Mar 24, 2013 at 09:14 AM
Perhaps something like this? Would differ if you would use physics.
public Transform gotoPosition;
private Transform oldPosition;
private float percentage = 0.0f;
public float speed = 0.1f;
public bool collided = false;
void Update() {
if (collided && percentage < 100.0f) {
if (percentage == 0) oldPosition = transform.position;
float percentageIncrease = Time.deltaTime * speed;
transform.position += (gotoPosition - oldPosition) * percentageIncrease;
percentage += percentageIncrease;
}
}
// Second script for the trigger
public GameObject player;
public GameObject box;
void OnTriggerEnter(Collider collider) {
if (collider.gameObject == player) {
AboveScriptName script = (AboveScriptName) box.getComponent("AboveScriptName");
script.collided = true;
}
}
that looks somewhat simpler than the other solutions I've seen, but I don't understand how to tell the trigger that I want THE BOX to move, not the trigger itself. Also, where do I specify the old and goto positions? Right now they don't appear to have a value...
Apply the trigger to a gameobject other than the box (and not the box as parent). Apply the script to the box, and set the gotoPosition to a (possibly empty deactivated) gameobject where you want the box to go to. $$anonymous$$ake sure there are rigidbodies attached (not necessary for the box).
This is code I wrote from the top of my head, so it might contain some errors in syntax.
http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Lerp.html http://docs.unity3d.com/Documentation/ScriptReference/Vector3.$$anonymous$$oveTowards.html
These two is if you want to have that a object goes from point A to B.
Answer by helloiam · Mar 24, 2013 at 11:01 AM
http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Lerp.html
Take a loot at this, maybe this will answer your question, you can also use MoveTowards
http://docs.unity3d.com/Documentation/ScriptReference/Vector3.MoveTowards.html
Your answer
Follow this Question
Related Questions
Moving an Object towards another Moving Object 2 Answers
How Can I Make a Moving Object with a trigger reaction ? [C#] 1 Answer
how to make a moving object 2 Answers
How can I move a corresponding object. 2 Answers
Emit Particle upon Death 2 Answers