1
\$\begingroup\$
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraRaycast : MonoBehaviour
{
    public Camera cam;

    public LineRenderer laserLineRenderer;
    public float laserWidth = 0.1f;
    public float laserMaxLength = 5f;

    void Start()
    {
        Vector3[] initLaserPositions = new Vector3[2] { Vector3.zero, Vector3.zero };
        laserLineRenderer.SetPositions(initLaserPositions);
        laserLineRenderer.startWidth = laserWidth;
        laserLineRenderer.endWidth = laserWidth;
    }

    void Update()
    {
        Ray ray = cam.ViewportPointToRay(cam.ScreenToViewportPoint(Input.mousePosition));
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 100))
            if (hit.transform.tag == "Interactable")
            {
                //print("I'm looking at " + hit.transform.name);
                laserLineRenderer.enabled = true;

                laserLineRenderer.SetPosition(0, ray.direction);
                laserLineRenderer.SetPosition(1, hit.transform.position);
            }
            else
            {
                //print("I'm looking at nothing!");
                laserLineRenderer.enabled = false;
            }
    }
}

When it detect a "Interactable" object i want it to draw green line from the mouse cursor to the point where the raycast is hitting.

Now it's not drawing anything.

\$\endgroup\$
  • \$\begingroup\$ If you need draw a line only for debugging, you could use Debug.DrawLine(docs.unity3d.com/ScriptReference/Debug.DrawLine.html) \$\endgroup\$ – whoo24 Nov 9 '17 at 8:25
  • 1
    \$\begingroup\$ You should use ray.origin at index 0 instead ray.direction. \$\endgroup\$ – whoo24 Nov 9 '17 at 8:28
  • \$\begingroup\$ @whoo24 ray.origin draw a line but to the original position i wasand i want to draw a line from my current mouse cursor position to the hitting point("Interactable"). \$\endgroup\$ – Daniel Lip Nov 9 '17 at 9:40
  • 1
    \$\begingroup\$ ray.origin is world position of mouse point. \$\endgroup\$ – whoo24 Nov 9 '17 at 9:56
1
\$\begingroup\$
  1. Create a Render Texture or Image.
  2. Take hit points from raycast and change the pixels of Image/Render Texture using Texture2D.SetPixel
  3. To make line visible you can change pixels around the hit point. It will be line width functionality (Commonly used brush size).
  4. You can use GL.Lines
  5. You can use already available unity assets like Easy 2D Lines, Mobile Paint
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.