P
P
PsyDuckbest2021-09-14 22:30:50
C++ / C#
PsyDuckbest, 2021-09-14 22:30:50

How to make a laser in Unity?

Hello. I'm trying to implement a laser pointer in the game and even Google does not work, at least in my hands. Sounds like a simple task for Raycast, but inside the game it is not visible and even there is little information on this topic, or the examples are not at all similar to mine. I work in 2D.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Zaletsky, 2021-09-15
@JZ_52

Raycast will not show you a beam (laser), it's just a feature that is very useful for such tasks. You need here is the video

F
Farawa, 2021-09-15
@Farawa

you will need 2 things: Physics.Raycast and a LineRenderer component.

public class Laser : MonoBehaviour
{
    [SerializeField] private LineRenderer lineRenderer;

    private void Update()
    {
        //Ray ray = new Ray(origin,direction);
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {
            lineRenderer.enabled = true;
            var firstPosition = Camera.main.transform.position;
            var secondPosition = hit.point;
            lineRenderer.SetPosition(0, firstPosition);
            lineRenderer.SetPosition(1, secondPosition);
        }
        else
        {
            lineRenderer.enabled = false;
        }
    }
}

6141adf5a61a8592586606.png6141ae1d6ad74507132609.png
LineRenderer has materials, you can create a material and throw it there and it will be the color you want

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question