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.

3 Answers

3

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. Make 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.MoveTowards.html These two is if you want to have that a object goes from point A to B.

–

Take a loot at this, maybe this will answer your question, you can also use MoveTowards

The trigger is easy that is what you have to find out for yourself