How do you add a Collider2D to a Line Renderer In Unity2D?
I am currently working on a project where you draw using a line renderer. I need to be a to have collisions for my idea to work. I have looked all over the internet but yet nothing has seemed to work. I have provided the code bellow. Thank you for your time.
public class Draw : MonoBehaviour
{
public Camera m_camera;
public GameObject brush;
LineRenderer currentLineRenderer;
Vector2 lastPos;
public AudioSource Splash;
public void Start()
{
var mesh = new Mesh();
var meshCollider = currentLineRenderer.gameObject.AddComponent<MeshCollider>();
currentLineRenderer.BakeMesh(mesh, true);
meshCollider.sharedMesh = mesh;
}
private void Update()
{
Drawing();
}
void Drawing()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
CreateBrush();
}
else if (Input.GetKey(KeyCode.Mouse0))
{
PointToMousePos();
}
else
{
currentLineRenderer = null;
}
}
void CreateBrush()
{
GameObject brushInstance = Instantiate(brush);
currentLineRenderer = brushInstance.GetComponent<LineRenderer>();
//because you gotta have 2 points to start a line renderer,
Vector2 mousePos = m_camera.ScreenToWorldPoint(Input.mousePosition);
currentLineRenderer.SetPosition(0, mousePos);
currentLineRenderer.SetPosition(1, mousePos);
}
void AddAPoint(Vector2 pointPos)
{
currentLineRenderer.positionCount++;
int positionIndex = currentLineRenderer.positionCount - 1;
currentLineRenderer.SetPosition(positionIndex, pointPos);
}
void PointToMousePos()
{
Vector2 mousePos = m_camera.ScreenToWorldPoint(Input.mousePosition);
if (lastPos != mousePos)
{
AddAPoint(mousePos);
lastPos = mousePos;
}
}
}
Comment