- Home /
Draw Line In GameView Point to point
I want to draw a line in Game View On Each Collision Point on a mouse click Like Every Where i click it draws a line from prev point to currnt point Measuring the distance btween these point IS it possible? if yes then help me get started i m experimenting with raycast rightnw Any help wud be Greatly Appriciated `
Answer by clunk47 · Jan 30, 2014 at 10:13 PM
For this example, I'm using a Ray, RaycastHit, and Vector3.Distance. I'm simply creating a new LineRenderer object each time you click on 2 different colliders. This measures the distance between the hit point of each transform, not just the transforms themselves. If you just want the transforms' positions to be measured, remove h0 and h1 and just use p0.position and p1.position as the Vector3.Distance parameters. I just used a scene w/ some cubes for testing.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Example : MonoBehaviour
{
Ray ray;
RaycastHit hit;
Transform p0 = null;
Transform p1 = null;
Vector3 h0;
Vector3 h1;
int i = 0;
Transform container;
float distance;
string label = "";
void Start()
{
container = new GameObject("Lines").transform;
}
void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit) && Input.GetMouseButtonDown(0))
{
if(!p0 && !p1)
{
p0 = hit.transform;
h0 = hit.point;
return;
}
if(p0 && !p1)
{
p1 = hit.transform;
h1 = hit.point;
}
if(p0 && p1)
{
LineRenderer line = new GameObject("Line " + i.ToString()).AddComponent<LineRenderer>();
line.transform.parent = container;
line.SetWidth(0.025F, 0.025F);
line.SetColors(Color.red, Color.green);
line.SetVertexCount(2);
line.SetPosition(0, h0);
line.SetPosition (1, h1);
distance = Vector3.Distance(h0, h1);
label = "Distance between hit point 0 of " + p0.name + " and hit point 1 of " + p1.name + " = " + distance.ToString ();
p1 = null;
p0 = null;
}
}
}
void OnGUI()
{
if(GUILayout.Button ("Reset"))
{
foreach(Transform lineObject in container)
{
Destroy(lineObject.gameObject);
}
}
GUILayout.Label(label);
}
}
Thankyou So $$anonymous$$uch for your input It is soo help full but a littel problem is that i want the distance of two hit points on a same mesh sorry for nt mentioning it in my question can you give any help on this Otherwise you script is working marvlously Thanks for support
Note you can remove the SetColors() instruction, since I didn't add a material to the LineRenderer in this code. I'll edit here in a bit to take out anything unnecessary.