I’m making a little game about lasers for fun and have run into an inconvenience with my splitters.
The point of the splitter is to reflect the laser and also allow it to pass through it at the same time.
But the way I have made it work makes it that it gets trapped if i start the raycast where i hit from the last.
My solution was to start the raycast 1 unit in the previous direction past the splitter because the objects are movable & spinable by the player and is about 1 unit long. Here is a picture, the light blue rectangle s are my splitters. I use gizmos to help visualize my raycasting.
heres my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Laser : MonoBehaviour
{
public int maxReflectionCount = 5;
public int maxSplitCount = 5;
public float maxStepDistance = 100;
private void OnDrawGizmos()
{
if (!Application.isPlaying)
{
return;
}
DrawPredictedReflection(this.transform.position, this.transform.up, maxReflectionCount, maxSplitCount);
}
void DrawPredictedReflection(Vector2 position, Vector2 direction, int reflectionsRemaining, int splitsRemaining)
{
var gizmoHue = (reflectionsRemaining / (this.maxReflectionCount + 1f));
Gizmos.color = Color.HSVToRGB(gizmoHue, 1, 1);
RaycastHit2D hit2D = Physics2D.Raycast(position, direction, maxStepDistance);
if (hit2D) //did we hit somthing?
{
Gizmos.DrawLine(position, hit2D.point);
Gizmos.DrawWireSphere(hit2D.point, 0.25f);
if (hit2D.transform.gameObject.tag == "Receiver")
{
Debug.Log("Receiver hit");
}
if (hit2D.transform.gameObject.tag == "Mirror") //mirror hit. set new pos where hit. reflect angle and make that new direction
{
Debug.Log("Mirror Hit");
direction = Vector2.Reflect(direction, hit2D.normal);
position = hit2D.point + direction * 0.01f;
if (reflectionsRemaining > 0)
DrawPredictedReflection(position, direction, --reflectionsRemaining, splitsRemaining);
}
if (hit2D.transform.gameObject.tag == "Splitter") //reflect and go ahead
{
Debug.Log("Splitter hit");
if (splitsRemaining > 0)//go ahead
{
Debug.Log("Splitting");
Vector2 splitPosition = hit2D.point + direction * 1f;
DrawPredictedReflection(splitPosition, direction, reflectionsRemaining, --splitsRemaining);
}
direction = Vector2.Reflect(direction, hit2D.normal);
position = hit2D.point + direction * 0.01f;
if (reflectionsRemaining > 0)//reflect too
{
DrawPredictedReflection(position, direction, --reflectionsRemaining, splitsRemaining);
}
}
}
}
}
I’ll accept all help and/or if you spot a way to optimize my script please let me know!