Portals

First off, use code tags:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PortalTeleporter : MonoBehaviour
{

    public Transform player;
    public Transform receiver;

    private bool playerIsOverlapping = false;

    // Update is called once per frame
    void Update()
    {
        if (playerIsOverlapping)
        {
            Vector3 portalToPlayer = player.position - transform.position;
            float dotProduct = Vector3.Dot(transform.up, portalToPlayer);

            if (dotProduct < 0f)
            {
                float rotationDiff = -Quaternion.Angle(transform.rotation, receiver.rotation);
                rotationDiff += 180;
                player.Rotate(Vector3.up, rotationDiff);

                Vector3 positionOffset = Quaternion.Euler(0f, rotationDiff, 0f) * portalToPlayer;
                player.position = receiver.position + positionOffset;

                playerIsOverlapping = false;
            }
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            playerIsOverlapping = true;
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.tag == "Player")
        {
            playerIsOverlapping = false;
        }

    }
}

Also, why is the actual teleport done in ‘Update’? This could all be done in OnTriggerEnter.

Also, why are you limiting yourself to having to reference the player directly, but check the Collider for the tag. Why not get the target from the Collider, and that way you can make the portal work for any range of entities that intersect it that meet some requirement (tag, layer, what not). Rather than only supporting a single object, the player.

Also you might want to add functionality to handle multi-directional portals. Otherwise you might trigger the portal’s targets return trigger box.

2 Likes