- Home /
Line Renderer hit detection?
@script RequireComponent (LineRenderer)
var mouse : Vector2;
var hit : RaycastHit;
var range : float = 100.0;
var line : LineRenderer;
var lineMaterial : Material;
var ray : Ray;
function Start()
{
line = GetComponent(LineRenderer);
line.SetVertexCount(2);
line.renderer.material = lineMaterial;
line.SetWidth(0.1f, 0.25f);
}
function Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, hit, range))
{
if(Input.GetMouseButton(1))
{
line.enabled = true;
line.SetPosition(0, transform.position);
line.SetPosition(1, hit.point + hit.normal);
}
else
line.enabled = false;
}
}
this isnt my script but im trying to modify this. at the moment the line goes through all objects, which isnt what i want. what would i need to add to stop the line going through objects. (currently my camera is setup for isometric) thanks in advance.
This is a script from a pool game I made, it is drawing a line from the player ball to wherever it hits in the raycast, this works so you should be able to adapt it.
function subDraw_Aim() {
var hit : RaycastHit;
if (Physics.Raycast (transform.position, -transform.forward, hit)) {
oAim_LineRenderer.SetPosition(0, transform.position);
oAim_LineRenderer.SetPosition(1, hit.point);
}
}
oAim_LineRenderer is my line renderer object.
A few lines from one of my scripts.
public void Shoot () {
RaycastHit hit;
float shotDistance = hit.distance;
if (Physics.Raycast(ray, out hit, shotDistance)) {
shotDistance = hit.distance;
}
}
Andrewlo3 is using C# by the look of it, and you are using js. $$anonymous$$y example is js so will prob suit you better.
The problem is not the language, more likely the result and the clarity. Though your comment (which should be an answer btw) may help, I would not think it solves entirely since it lacks some explanation. You cast from the object towards the -forward, so you need to rotate the object properly first. I guess because you were using the direction of the queue in your pool game, that worked.
Here it would be to cast from the object to the hit point of the camera ray.
var hitPoint:Vector3;
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Input.Get$$anonymous$$ouseButton(1) && Physics.Raycast(ray, hit, range))
{
hitPoint = hit.point;
}
if(Physics.Linecast(transform.position, hitPoint, hit))
{
// Colliders in between
// Draw from transform to hit.point
}else{
// No colliders in between
// Draw from transform to hitPoint
}
What you do is take the hit from the camera cast, then try to join the object to that point with a linecast, then if there are a hit, it returns true and you draw from your object to the hit, if free all the way you draw from object to camera hit.
(This should be an answer...)
@fafase I left $$anonymous$$e as a comment because I knew it was not a copy paste solution, but rather a good starting point.