I would like to be able to draw a line with my finger, and when I lift my finger a collider is added to it. The line could be a squiggly line or straight line, it all depends on what is needed. but basically I wan’t to be able to create as many lines as I want, and each line will have it’s own collider. I am pretty sure it is possible to do that, but the question is how?
Basically you use your finger to create ground/walls in the game.
I found this: Draw Line on mouse move and detect line collision in unity 3D
Which allows me to draw a line, now I just need to be able to place a collider around it and create multiple lines…
I Was able to build it, and if anyone is looking for something similar, here is the code. Just attach it to an empty game object.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DrawLine : MonoBehaviour {
private LineRenderer line;
private bool isMousePressed;
private GameObject lineObject;
private List<Vector3> pointsList;
private Vector3 mousePos;
private float lineSize = 0.25f;
void Update () {
// If mouse button down, remove old line and set its color to green
if(Input.GetMouseButtonDown(0)){
isMousePressed = true;
newLine();
}
else if(Input.GetMouseButtonUp(0)){
isMousePressed = false;
}
// Drawing line when mouse is moving(presses)
if(isMousePressed){
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
if(!pointsList.Contains(mousePos)){
pointsList.Add(mousePos);
line.SetVertexCount(pointsList.Count);
line.SetPosition(pointsList.Count - 1, (Vector3)pointsList[pointsList.Count - 1]);
Vector3 point1 = pointsList[pointsList.Count - 2];
Vector3 point2 = pointsList[pointsList.Count - 1];
GameObject obj = new GameObject("SubCollider");
obj.transform.position = (point1 + point2) / 2;
obj.transform.right = (point2 - point1).normalized;
BoxCollider2D boxCollider = obj.AddComponent<BoxCollider2D>();
boxCollider.size = new Vector3((point2 - point1).magnitude, lineSize, lineSize);
obj.transform.parent = lineObject.transform;
}
}
}
void newLine(){
lineObject = new GameObject();
lineObject.name = "Line";
lineObject.transform.parent = gameObject.transform;
line = lineObject.AddComponent<LineRenderer>();
line.material = new Material(Shader.Find("Sprites/Default"));
line.SetVertexCount(0);
line.SetWidth(lineSize, lineSize);
line.SetColors(Color.black, Color.black);
line.useWorldSpace = true;
pointsList = new List<Vector3>();
}
}