Right now your code is "raycast hit something: reflect unconditionally." If you want it to only reflect off mirrors you need to add some code:
//...
//Check if the ray has hit something
if (Physics.Raycast(ray.origin, ray.direction, out hit, 100))//cast the ray 100 units at the specified direction
{
//the refletion direction is the reflection of the ray's direction at the hit normal
direction = Vector3.Reflect(direction, hit.normal);
//cast the reflected ray, using the hit point as the origin and the reflected direction as the direction
//NEW!
//if the ray hit a mirror, reflect! Otherwise do nothing.
if(hit.transform.name == "Mirror") {
ray = new Ray(hit.point, direction);
}
else {
i = 9999; //not the best, see additional comments
}
//Draw the normal - can only be seen at the Scene tab, for debugging purposes
Debug.DrawRay(hit.point, hit.normal * 3, Color.blue);
//represent the ray using a line that can only be viewed at the scene tab
Debug.DrawRay(hit.point, direction * 100, Color.magenta);
//Print the name of the object the cast ray has hit, at the console
// Debug.Log("Object name: " + hit.transform.name);
//add a new vertex to the line renderer
lineRenderer.positionCount = ++numPoints;
//set the position of the next vertex at the line renderer to be the same as the hit point
lineRenderer.SetPosition(i + 1, hit.point);
}
//...
By setting i
to 9999, it means that the code will treat this loop as the last one, it will finish drawing this portion of the line, then terminate. This isn't the best way to do this, but it leaves your code laid out the same way it already was. If the if(hit == "mirror")
section is moved to the end of its parent section, then we can do else { break; }
instead, which will break out of the for-loop early.
You'll have to do this in both halves of your update loop, as you have a "if hasn't yet bounced" versus "has previously bounced" sections which are largely identical.