I want to create portals where, if a GameObject falls into one of the portals, it comes out through another. The problem is keeping my hierarchy clean and manageable. I haven’t attached the colliders to the parent object itself; instead, I’ve created child objects with colliders (I didn’t want to use mesh colliders). When the colliders are attached to the parent object, the collision gets triggered, but when the colliders are child objects, it doesn’t. Is there a way to make teleportation happen this way?
Thank you!
using UnityEngine;
public class Portal : MonoBehaviour
{
[SerializeField] private Transform _linkedPortal;
[SerializeField] private float _teleportOffset = 0.5f;
private void OnTriggerEnter(Collider other)
{
if (_linkedPortal != null && other.CompareTag("Car"))
{
HandlePortal(other);
}
}
private void HandlePortal(Collider carCollider)
{
Rigidbody rb = carCollider.GetComponent<Rigidbody>();
if (rb != null)
{
Vector3 currentRotation = carCollider.transform.eulerAngles;
Quaternion rotationDiff = _linkedPortal.rotation * Quaternion.Inverse(transform.rotation);
Vector3 newVelocity = rotationDiff * rb.velocity;
Vector3 offset = _linkedPortal.forward * _teleportOffset;
carCollider.transform.position = _linkedPortal.position + offset;
carCollider.transform.rotation = Quaternion.Euler(currentRotation.x, currentRotation.y, rotationDiff.eulerAngles.z);
rb.velocity = newVelocity;
Debug.Log("Car teleported through portal!");
}
}
private void OnDrawGizmos()
{
if (_linkedPortal != null)
{
Gizmos.color = Color.cyan;
Gizmos.DrawLine(transform.position, _linkedPortal.position);
Gizmos.color = Color.blue;
Gizmos.DrawRay(transform.position, transform.forward);
}
}
}