Step 1. Create an empty GameObject with Line Renderer attached to it.
Step 2. Create an child GameObject to above with BoxCollider attached to it.
Step 3. Attach the below script to mainCamera
using UnityEngine;
using System.Collections;
public class MakeALine : MonoBehaviour {
public GameObject lineParent;
GameObject colliderObject ;
Vector3 pos1, pos2 ;
LineRenderer line ;
void Start () {
line = lineParent.GetComponent<LineRenderer>() as LineRenderer;
colliderObject = lineParent.transform.FindChild("BoxCollider").gameObject;
}
void Update () {
if(Input.GetMouseButtonDown(0)){
pos1 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos1.z = 0;
line.SetPosition(0, pos1);
line.SetPosition(1, pos1);
}
else if(Input.GetMouseButton(0)){
pos2 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos2.z = 0;
line.SetPosition(1, pos2);
}
if(Input.GetMouseButtonUp(0)){
CreateAndSetCollider();
}
}
void CreateAndSetCollider(){
//Adjusting the length of the collider according to the length of line made
float length = Vector3.Distance(pos1, pos2) ;
colliderObject.transform.localScale = new Vector3(length, .2f, 1) ;// setting the size of collider
Vector3 midPoint = (pos1+pos2) / 2 ;
colliderObject.transform.position = midPoint ;
colliderObject.transform.rotation = line.transform.rotation ;
//Adjusting the length of the collider according to the length of line DONE=======
//Adjusting the angle of the collider according to the length of line made
float angle = (Mathf.Abs (pos1.y - pos2.y) / Mathf.Abs (pos1.x - pos2.x));
if((pos1.y<pos2.y && pos1.x>pos2.x) || (pos2.y<pos1.y && pos2.x>pos1.x))
{
angle*=-1;
}
angle = Mathf.Rad2Deg * Mathf.Atan (angle);
colliderObject.transform.Rotate (0, 0, angle);
//Adjusting the angle of the collider according to the length of line made=======
}
}
Step 4. Drag and Drop parent object to the public object declared in the Script.
That's it ....Run your scene and Draw a line on it. A line gets created with a proper Box collider on it.
0 Comment(s)