- Home /
Question by
Thorin1904 · Jan 04, 2021 at 01:13 PM ·
2draycastcolliderlinerendererline renderer
Detecting if the object is hit by LineRenderer
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?
Comment
Answer by prakyathd801 · Jan 04, 2021 at 01:27 PM
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 : https://www.youtube.com/watch?v=pa_U64G7gkE Note: This is to draw line on swiping the screen, modify it as per your requirement
Your answer
Follow this Question
Related Questions
Top down shooter: Laser Sight 1 Answer
Line Renderer Ending In the Center 0 Answers
Raycast on a 2D Collider 7 Answers