Ray Reflection system not work correctly.
Hello everyone. I design a reflection system based on Ray2D. when the ray casts toward an object, if the object's tag is "mirror", the ray reflects and if the tag is "barrier" the ray stops right at the hit point of the barrier object. when I rotate the ray source, the system works perfectly as you see in 12.jpg
the source is the blue painting.
but a huge bug is occured when the source is rotated to some angle like 13.jpg
here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(LineRenderer))]
public class LaunchingLaser : MonoBehaviour
{
public int reflections;
public float maxLength;
public List<Vector2> hit_points;
private LineRenderer line;
private Ray2D ray;
private RaycastHit2D hit;
private Vector2 direction;
private void Awake()
{
line = gameObject.GetComponent<LineRenderer>();
}
private void LateUpdate()
{
hit_points = new List<Vector2>();
ray = new Ray2D(transform.position, transform.up);
line.positionCount = 1;
line.SetPosition(0, transform.position);
float remainingLength = maxLength;
hit = Physics2D.Raycast(ray.origin, ray.direction, remainingLength);
hit_points.Add(hit.point);
//Debug.Log(hit.collider.tag.ToString());
for (int i = 0; i < reflections; i++)
{
if (hit.collider.tag == "mirror")
{
//Debug.Log(hit.point.ToString());
line.positionCount += 1;
line.SetPosition(line.positionCount - 1, hit.point);
remainingLength -= Vector2.Distance(ray.origin, hit.point);
ray = new Ray2D(hit.point, Vector2.Reflect(ray.direction, hit.normal));
hit = Physics2D.Raycast(ray.origin, ray.direction, remainingLength);
hit_points.Add(hit.point);
}
else
{
line.positionCount += 1;
line.SetPosition(line.positionCount - 1, hit.point);
break;
}
}
}
}
I set the maxLength to 100 and reflections to 5. I also insert the hit positions in a list of vector2. The hit position list for 12.jpg is OK and it shows the hit positions perfectly. but for 13.jpg the hit position list has 5 element and all of them have same value. I have the image of them but I can't attach it to the post neither the comment because of attachment restrictions.