rays reflection in 2d game unity cover image

Reflecting Rays in 2D game

Many games are available in the store that is based on the principle of reflection. They use simple, yet intuitive designs to showcase reflecting rays in the game.

In this article, I will be explaining how we can also create rays reflection in a 2D game in Unity.

Before getting started, have a glimpse of what you are going to make in this article.

reflecting rays in 2d game

Beginning with the Setup

The article explains reflection of rays in a 2D game so make sure your camera is in Orthographic projection mode before proceeding.

Creating the Rays Reflection

Create an empty gameobject and attach a Line Renderer to it. Now adjust the properties of the Line Renderer as per your need. This line renderer will be used to draw original rays and their reflection. You may set the width/material of the line renderer.

After making some adjustments, the line drawn by line renderer looks like the image below.

line renderer for rays

Setting up the Rays Reflection

Now we have a gameobject with a line renderer on it. Now we will use this gameobject to make reflections.

Create a new script named ReflectRays.cs and replace the content of the script with the following code.

using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class ReflectRays : MonoBehaviour
{
    const int Infinity = 999;

    int maxReflections = 100;
    int currentReflections = 0;

    [SerializeField]
    Vector2 startPoint, direction;
    List<Vector3> Points;
    int defaultRayDistance = 100;
    LineRenderer lr;

    // Use this for initialization
    void Start()
    {
        Points = new List<Vector3>();
        lr = transform.GetComponent<LineRenderer>();
    }

    private void Update()
    {
        var hitData = Physics2D.Raycast(startPoint, (direction - startPoint).normalized, defaultRayDistance);

        currentReflections = 0;
        Points.Clear();
        Points.Add(startPoint);

        if (hitData)
        {
            ReflectFurther(startPoint, hitData);
        }
        else
        {
            Points.Add(startPoint + (direction - startPoint).normalized * Infinity);
        }

        lr.positionCount = Points.Count;
        lr.SetPositions(Points.ToArray());
    }

    private void ReflectFurther(Vector2 origin, RaycastHit2D hitData)
    {
        if (currentReflections > maxReflections) return;

        Points.Add(hitData.point);
        currentReflections++;

        Vector2 inDirection = (hitData.point - origin).normalized;
        Vector2 newDirection = Vector2.Reflect(inDirection, hitData.normal);

        var newHitData = Physics2D.Raycast(hitData.point + (newDirection * 0.0001f), newDirection * 100, defaultRayDistance);
        if (newHitData)
        {
            ReflectFurther(hitData.point, newHitData);
        }
        else
        {
            Points.Add(hitData.point + newDirection * defaultRayDistance);
        }
    }
}

Now attach the script to the gameobject containing the line renderer and set the Start Point to (-10, 10) and Direction to (0, 0). This means our ray will originate from coordinate (-10, 10) towards the Direction coordinate.

Now run the game, you will see a ray crossing through the scene something like this.

ray created from source towards direction

Creating Reflections

To create rays reflections, simply create a Sprite and attach a 2D collider to it and position that sprite to cut the ray. You will see the rays reflecting as soon as the sprite coincides the rays.

reflecting rays in 2d game

Buy me a cup ☕ of coffee @ paypal.me/KunalTandon94, it keeps me motivated and keeps this blog running.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.