Reflecting object through portal and matching exit portal rotation
I'm trying to create a 2d portal. I have my portal object with it's Vector.up. I reflect the original cube along this vector to see how far the object has passed through the portal. Problem is, I can transport a cloned object to the exit portal, it's rotation matches that of the exit portal, but its positioning is off.
This here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ReflectAlong : MonoBehaviour
{
public GameObject reflectionObj; // The portal
public GameObject clonePrefab; // CubePrefab to spawn at exit portal
public GameObject exitPoint; // Exit Portal
private GameObject clone; // Copy of the original cube coming out of the portal
void Start()
{
if (reflectionObj)
{
Vector2 transformVector = Vector2.Reflect((reflectionObj.transform.position - transform.position), reflectionObj.transform.up);
Quaternion newRotation = Quaternion.LookRotation(transformVector, transform.up) * exitPoint.transform.rotation;
var euler = exitPoint.transform.rotation.eulerAngles; // get target's rotation
var rot = Quaternion.Euler(0, 0, euler.z); // transpose values
clone = Instantiate(clonePrefab, new Vector3(transformVector.x, transformVector.y, 0) + exitPoint.transform.position, rot);
}
}
// Update is called once per frame
void Update()
{
if (clone)
{
// Match the portal rotation for the cloned cube
var euler = exitPoint.transform.rotation.eulerAngles; //get target's rotation
var rot = Quaternion.Euler(0, 0, euler.z); //transpose values
clone.transform.rotation = rot;
// Mirror the original cube along the portal vector.up then move it to the exit portal.
Vector3 transformVector = Vector3.Reflect((reflectionObj.transform.position - transform.position), reflectionObj.transform.up);
clone.transform.position = new Vector3(transformVector.x, transformVector.y, 0) + exitPoint.transform.position;
}
}
}
I feel like I'm maybe close but not really. If you look at the image, the dark cube should be moved to the blue outline, being as far away from the exit portal's back as the original cube is away from the entry portal. The rotation on the cube is 90 degrees on Z, just as the exit portal, so that's okay.
Can anyone help me out? :/ Thank you!
Your answer
Follow this Question
Related Questions
Checking if the reflected angle is too sharp 0 Answers
Rotate a game scene preserving all physics ,Rotate scene preserving all game structure (physics) 1 Answer
How to write a surface shader for realtime reflection? (CG) 0 Answers
How to transform a GameObject to an Empty GameObject's position and rotation 1 Answer