Placing player relative to object,Placing the player relative to an object

I’m making a game where a first person player walks around a city, when he enters the trigger of a door i want him to be placed in front of it.
The problem is all the doors are positioned and rotated differently and i can’t figure out a way to write general code for the placement.,I’m making a game with a first person player walking around a city, when he finds a door and starts interacting with it by pressing a key i want his position to change so he’s in front of the door.
I can’t figure out how to write a general code for it since every door is in a different position and rotation.

One way to go about it is to place an empty game object (under the door hierarchy) that has the correct position and rotation relative to the door. You can then copy its position and rotation to the player when the player interacts with the door.


Another way is to move the player to the door’s position and rotation and then offset the player’s position along the player’s local “forward”-axis. (You can also offset the rotation by 180 degrees when they interact with the door from the other side.)

This makes the player align to the doors trigger collider Transform, which should be placed inside the door hierarchy and moved on Local Z away from it. Make also sure that the boxcolliders Z Axis is pointing to the door. Or Use transform.LookAt(doorTrigger.parent); to look at the door directly.

Place this in the playerscript:

Transform doorTrigger;

void Update(){
    if(doorTrigger){
        if(Input.GetKeyDown(KeyCode.Space)){
            transform.SetPositionAndRotation(doorTrigger.position, doorTrigger.rotation);
        }
    }
}

void OnTriggerEnter(Collider col){

    if(col.gameObject.tag == "DoorTrigger")
        doorTrigger = col.transform;
}

void OnTriggerExit(Collider col){

    if(col.gameObject.tag == "DoorTrigger")
        doorTrigger = null;
}

You could make also a new MonoBehaviour DoorChecker.cs that activates itself when door is found. Remember that OnTriggerXXX(Collider col) are called even if the script is disbaled. Therefore Update() runs only if a door Transform is not null:

public class DoorChecker : MonoBehaviour {

    Transform doorTrigger;
    void Awake(){ this.enabled = false; }
    void Update(){
        if(Input.GetKeyDown(KeyCode.Space)){
            transform.SetPositionAndRotation(doorTrigger.position, doorTrigger.rotation);
        }
    }

    void OnTriggerEnter(Collider col){

        if(col.gameObject.tag == "DoorTrigger"){
            doorTrigger= col.transform;
            this.enabled = true;
        }
    }

    void OnTriggerExit(Collider col){

        if(col.gameObject.tag == "DoorTrigger"){
            doorTrigger= null;
            this.enabled = false;
        }
    }
 }