Hi I’m making a 2D reflection game and there is a light renderer that touches my blocks and I want to add the block’s script if it is hit by the line renderer or not but Line Renderer has not collider and I don’t know how to detect line render with other objects. Do you guys have any suggestions?
Here’s script that creates the line and adds collider to it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyLineDraw : MonoBehaviour
{
public GameObject linePrefab;
public GameObject currentLine;
public LineRenderer lineRenderer;
public EdgeCollider2D edgeCollider;
public List<Vector2> fingerPositions;
private void Update() {
if(Input.GetMouseButtonDown(0))
{
CreateLine();
}
if(Input.GetMouseButton(0))
{
Vector2 tempFingerpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if(Vector2.Distance(tempFingerpos, fingerPositions[fingerPositions.Count-1])>0)
{
UpdateLine(tempFingerpos);
}
}
}
void CreateLine()
{
currentLine = Instantiate(linePrefab, Vector3.zero, Quaternion.identity);
lineRenderer = currentLine.GetComponent<LineRenderer>();
edgeCollider = currentLine.GetComponent<EdgeCollider2D>();
fingerPositions.Clear();
fingerPositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition));
fingerPositions.Add(Camera.main.ScreenToWorldPoint(Input.mousePosition));
lineRenderer.SetPosition(0, fingerPositions[0]);
lineRenderer.SetPosition(1, fingerPositions[1]);
edgeCollider.points = fingerPositions.ToArray();
}
void UpdateLine(Vector2 newFingerPos)
{
fingerPositions.Add(newFingerPos);
lineRenderer.positionCount++;
lineRenderer.SetPosition(lineRenderer.positionCount-1, newFingerPos);
edgeCollider.points = fingerPositions.ToArray();
}
}
For more info check this : Unity Drawing Lines with Mouse Position - Line Renderer and Edge Collider - YouTube
Note: This is to draw line on swiping the screen, modify it as per your requirement