The usual way is to place the target position marker outside the entrance trigger of the other side. Most FPS games ( like Quake3 for example ) do it this way.
var destination : Transform;
function OnTriggerEnter(aPlayer : Collider)
{
var oldPlayerRotation = transform.InverseTransformDirection(aPlayer.transform.forward);
aPlayer.transform.forward = destination.TransformDirection(oldPlayerRotation);
aPlayer.transform.position = destination.position;
if (aPlayer.rigidbody != null)
{
var oldPlayerVelocity = transform.InverseTransformDirection(aPlayer.rigidbody.velocity);
aPlayer.rigidbody.velocity = destination.TransformDirection(oldPlayerVelocity);
}
}
So you need 4 GameObjects in total. Two Triggers (BoxCollider) and each of them should have this script attached. In addition you need two empty GameObjects which mark the destination of the teleporter. You can parent the empty GO to the trigger. Make sure that the destination marker is outside of the trigger and add the radius of you player. So when you place the player at the destination position he’s outside of the trigger.
Now just link the destination markers to the “destination” variable of the other trigger.
Something like that:
It’s of course possible to omit the destination markers and add a manual offset to the target position to make sure it’s outside of the trigger, but this way it’s way more flexible. You can make teleport chains. Imagine 3 teleporters: TP1 goes to TP2, TP2 goes to TP3 and TP3 goes to TP1. It’s also very easy to make a one way tp as well. Essentially every teleporter is one way, you just have two of them
If you have this object as a prefab (I’m treating this script as Teleport.js):
var destination : Transform;
var prefab : GameObject = null;
private var instantiateOther : boolean = false;
function OnTriggerEnter (other : Collider) {
//if (other.CompareTag ("Player")) {
other.transform.position = destination.transform.position;
if(!instantiateOther && prefab != null){
var destinationObject = Instantiate (prefab, destination.transform.position, destination.transform.rotation);
var otherTeleport = destinationObject.GetComponent(Teleport);
otherTeleport.setInstantiateOther(true);
otherTeleport.destination = transform;
setInstantiateOther(true);
}
//}
}
function setInstantiateOther(value : boolean){
instantiateOther = value;
}
Maybe this code needs a condition to doesn’t start a loop, like a flag that is activate in OnTriggerExit and this flag need to be active for OnTriggerEnter works.