I am making a 2D unity game for school and wanted to create a laser-mirror puzzle where the player rotates mirrors to aim a laser around obstacles to get to an end point. I have used a line renderer to create the laser and used this code for the laser:
using UnityEngine;
public class Laser : MonoBehaviour
{
public Transform laserOrigin;
public LineRenderer lineRenderer;
public float maxLaserDistance = 100f;
private int solidObjectsLayer;
private Vector3 upDirection;
private bool isReflecting = false;
private Vector3 reflectionPoint;
private void Start()
{
lineRenderer.positionCount = 2;
lineRenderer.SetPosition(0, laserOrigin.position);
solidObjectsLayer = LayerMask.NameToLayer("SolidObjects");
upDirection = transform.up;
}
private void Update()
{
if (!isReflecting)
{
RaycastHit2D hit = Physics2D.Raycast(laserOrigin.position, upDirection, maxLaserDistance);
if (hit.collider)
{
lineRenderer.SetPosition(1, hit.point);
if (hit.collider.gameObject.layer == solidObjectsLayer)
{
isReflecting = true;
reflectionPoint = hit.point;
}
}
else
{
lineRenderer.SetPosition(1, laserOrigin.position + (upDirection * maxLaserDistance));
}
}
else
{
lineRenderer.SetPosition(1, reflectionPoint);
if (Vector3.Distance(laserOrigin.position, reflectionPoint) >= 0.01f)
{
laserOrigin.position = Vector3.MoveTowards(laserOrigin.position, reflectionPoint, Time.deltaTime * maxLaserDistance);
}
else
{
Vector3 reflectionDirection = Vector3.Reflect(upDirection, (reflectionPoint - laserOrigin.position).normalized);
upDirection = reflectionDirection;
isReflecting = false;
}
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.layer == solidObjectsLayer)
{
lineRenderer.enabled = false;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.layer == solidObjectsLayer)
{
lineRenderer.enabled = true;
}
}
}
I cannot figure out a way for the line renderer/laser to reflect of these ‘mirrors’. The way that I want them to reflect is the laser coming out of a specific point of the mirror, and not like a normal reflection where the angle at which the laser hits the mirror effects it. I also want to make it so if one mirror loses connection with the laser, the following lasers will be destroyed. I’ve tried making a script that means when the original laser touches the ‘mirror’ it creates another line renderer coming from the mirror, but it never works properly. I am also not sure if this is the place to post this question so if this is not the right spot, could you please direct me to a better place to post this. Thanks.
