Home > Software design >  Draw line between two game objects using linerenderer and raycast
Draw line between two game objects using linerenderer and raycast

Time:05-05

What I'm trying to do is draw line between two gameobjects I'm using ray distance and line renderer but the line is too long. Below is my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DrawLineTest : MonoBehaviour
{
    RaycastHit hit;

    public LineRenderer lineRender;

    private void Awake()
    {
        lineRender = GetComponent<LineRenderer>();
    }

    void Start()
    {
        Ray ray = new Ray(transform.position, Vector3.down);

        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider != null)
            {
                lineRender.enabled = true;

                lineRender.SetPosition(0, transform.position);
                lineRender.SetPosition(1, Vector3.down * hit.distance);

            }
        }
    }
}

enter image description here

CodePudding user response:

The second point is

lineRender.SetPosition(1, transform.position   Vector3.down * hit.distance);

or

lineRender.SetPosition(1, ray.GetPoint(hit.distance));

or more succinct

lineRender.SetPosition(1, hit.point);
  • Related