- Home /
Question by
Kunal6569 · Jun 02, 2018 at 09:50 AM ·
raycastreflectionline renderer
Can anybody tell me why reflections are not smoother from 2nd reflection? The first reflection is smooth but later ones aren't smooth. Please find the attached gif.
using System.Collections.Generic;
using UnityEngine;
public class ReflectingRays : MonoBehaviour
{
[SerializeField] int reflections;
bool drawRay = false;
List<Vector2> rays = new List<Vector2>();
Vector2? normal;
// Update is called once per frame
void LateUpdate()
{
if (!drawRay)
{
rays.Clear();
return;
}
if (rays.Count == 1) return;
int currentReflections = 0;
int rayIndex = 1;
while (reflections >= currentReflections && normal != null)
{
var direction = Vector2.Reflect(rays[rayIndex] - rays[rayIndex - 1], (Vector2)normal);
var hitPoint = Physics2D.Raycast(rays[rayIndex], direction);
Debug.DrawRay(rays[rayIndex], direction * 999);
if (hitPoint.collider != null)
{
currentReflections++;
normal = hitPoint.normal;
rays.Add(hitPoint.point);
}
else
{
normal = null;
}
rayIndex++;
}
drawRay = false;
}
public void DrawRay(Vector2 start, Vector2 end)
{
drawRay = true;
rays.Clear();
rays.Add(start);
var rayCastHit = Physics2D.Raycast(start, (end - start));
Debug.DrawRay(start, (end - start) * 999);
if (rayCastHit.collider != null)
{
normal = rayCastHit.normal;
rays.Add(rayCastHit.point);
}
else
{
normal = null;
}
}
}
reflecting-rays.gif
(324.1 kB)
Comment
Answer by Scribe · Jun 02, 2018 at 05:47 PM
So this is a guess but I think your raycasts might be originating just inside the collider you've just hit. You could test this theory pretty easily by changing line 30 to:
var hitPoint = Physics2D.Raycast(rays[rayIndex] + (direction.normalized * 0.01f), direction);
That adds a tiny movement in the decided direction, hopefully just enough to move 'outside' of the current collider.
If that works but you don't like the solution you could look into using a (dynamic?) layer mask instead