- Home /
Collider for Line Renderer?
Hello.
I need a collider component to attach to a line renderer so that I can detect raycasts onto the line area.
At the moment it would be sufficient to assume that the line is only one segment long, so I guess I could wrap something up with a box collider, scale it to the line thickness and transform it when the line positions change.
But I wonder whether there is an easier approch? Or maybe an already made collider that would cover multiple segments? (I probably want to have multi-segment line renderers later).
I am pretty new to Unity... How could I create and plug in my own Collider component? All tutorials I saw seem to only cover creating of C# or JavaScript script components? (I am familiar with C++/C as well, so that would not be a problem for me)
Edit: To clearify (if someone else stumble upon this), I am not facing the problem "What is my line renderer (e.g. a laser shot) hitting at this very moment?"
What my problem is: I want to shoot other raycasts (for example mouse clicks with NGUI) on the scene and they should detect whether the line was hit. And that's precisely what colliders are for. ;-)
Even writing a Script component that manages a list of Capsule or Box Collider for an existing LineRenderer is impossible, since there seem to be no functions to query the vertices of the line renderer - only Set* functions. Not cool :(. So basically, I must not configure the line renderer in Unity-Editor, but an own script that will create the renderer and the colliders dynamically?
I'm not quite sure what you mean with a line. But you can only add colliders to objects like spheres and cubes. A plane for example, has no collider. To solve your problem, you could use a cube and stretch it like a long line.
Since you said you are new to Unity, here is a beginner tutorial about colliders: http://unity3d.com/learn/tutorials/modules/beginner/physics/colliders
Can you post a pic of your line renderer? I cannot make sense of what you need. If your renderer is straight use a raycast.
A raycast does not help here. I do not want to detect collisions with other objects of the line the renderer is drawing. I want other raycasts to hit the drawn area.
But I already patched some sort of solution together by creating a capsule collider and aligning it the same as the line renderer (funny enough, I started out using a camera-aligned box ins$$anonymous$$d of a line renderer and replaced it for ease of use..) I will write some code together for others to reference and post it later.
Answer by Immanuel-Scholz · Jun 08, 2013 at 04:24 PM
So to answer my own question: There does not seem to be any support for installing own collider types.
But the same result can be somehow achieved by a script component instead that creates dynamically an capsule collider.
The tricky part here is, that you can not retrieve the vectors from the line renderer. Once they are set, they are not back accessible.
Luckily, that wasn't a very big problem for me, since I was updating the line renderer every frame with new start and end positions anyway.
So that's what I used:
// "attaches" a line renderer between two other game objects and also create
// a collider so you can cast raycasts on the line (or listen for collisions)
// only works for single-segment line renderers.
public class AttachLineRenderer : MonoBehaviour
{
public Transform start;
public Transform target;
LineRenderer line;
CapsuleCollider capsule;
public float LineWidth; // use the same as you set in the line renderer.
void Start()
{
line = GetComponent();
capsule = gameObject.AddComponent();
capsule.radius = LineWidth / 2;
capsule.center = Vector3.zero;
capsule.direction = 2; // Z-axis for easier "LookAt" orientation
}
void Update()
{
line.SetPosition(0, start.position);
line.SetPosition(1, target.position);
capsule.transform.position = start.position + (target.position - start.position) / 2;
capsule.transform.LookAt(start.position);
capsule.height = (target.position - start.position).magnitude;
}
}
A halfway solution, good when the start and end widths are equal. What to do when different?
the solution here couldn't be simpler. Just make a plane that is the shape you want (i.e. long and thin) and you're done. (Ideally, create a "perfect" two triangle plane for the purpose - any number of scripts available to do this.) Even better, simply use a cube (i.e., very long and flat) and you're done. All you have to do is programmatically resize the length, one line of code. This supern answer I wrote http://answers.unity3d.com/questions/432009/resizing-a-gameobject-based-on-mouse-position.html will help you do that very elegantly. Please vote it up as I need more points :)
But a the shape of the line segment is a trapeze, so how would you @Fattie turn a primitive plane or cube or box or capsule into a trapeze or cone?
(1) I don't know what you mean by a trapeze. Add a drawing to your question. (2) if you need a truly weird shape in a 3D game (say, a dragon or a squashed triangle or a s$$anonymous$$m train) you have your modelling department make the 3D model, and then you the programmer use it in the game. (3) if you want like a rectangle with points of the end (say) use primitive shapes to add up to it. (4) ultimately (although this is advanced) make any shape you want by building the mesh. (5) finally, it's almost inconceivable that a "rectangle" would not work perfectly, in any game. So use that. (6) also the shape of a line renderer is in fact "a rectangle". Note that overwhel$$anonymous$$gly, LineRenderer is totally wrong for this situation, so don't use it. A LR is a (cheap, rather useless) "billboard" (google) technology that Unity threw-in for debugging, etc. In a word, it's all but useless in production games.
I exactly mean that the shape of a line segment is not a rectangle, but trapeze. A rectangle is just a case of trapeze, when the line start and end widths are the same. So I agree the line renderer is not good for cases like that and just the mesh build from scratch could be a precisely working solution here.
Answer by bertrand_arnaud · Apr 11, 2019 at 12:33 PM
Since Unity 2018.2, you can now use the public method BakeMesh of LineRenderer. This will give you the mesh along the LineRenderer with all the segments. You can then use this mesh with a mesh collider in order to detect Collisions and Raycasts.
LineRenderer lineRenderer = line.GetComponent<LineRenderer>();
MeshCollider meshCollider = line.AddComponent<MeshCollider>();
Mesh mesh = new Mesh();
lineRenderer.BakeMesh(mesh, true);
meshCollider.sharedMesh = mesh;
I tested it and it worked on my project. Let me know what you think about it and if it helps you !
[Physics.PhysX] TriangleMesh::loadFromDesc: desc.isValid() failed! UnityEngine.StackTraceUtility:ExtractStackTrace ()
Answer by ZackOfAllTrades · Jun 06, 2017 at 07:54 AM
Here is a quick tutorial on how I solved this problem. First a list of what we need, write these down and fill them in:
startPoint of the line
endPoint of the line
lineLength which between these two points
lineWidth which you can get from the line renderer by calling YourLineRendererHere.endWidth
midPoint which is simply (startPoint + endPoint) / 2
slope which recall is (y2 - y1)/(x2-x1)
Thats It!
let's get the slope
y2 = endPoint.z
y1 = startPoint.z
x2= endPoint.x
x1 = startPoint.x
lets plug it in, don't calculate this just leave it slope = (endPoint.z - startPoint.z)/ (endPoint.x - startPoint.x)
!!! IMPORTANT !!!
In 3d space you use the x and z axis becuase the y is pointing up and we don't care about that. In 2d space you use the x and y axis, you would also use Vector2 points in your function not Vector 3
Here's your function--
private void AddColliderToLine(LineRenderer line, Vector3 startPoint, Vector3 endPoint)
{
//create the collider for the line
BoxCollider lineCollider = new GameObject("LineCollider").AddComponent<BoxCollider>();
//set the collider as a child of your line
lineCollider.transform.parent = line.transform;
// get width of collider from line
float lineWidth = line.endWidth;
// get the length of the line using the Distance method
float lineLength = Vector3.Distance(startPoint, endPoint);
// size of collider is set where X is length of line, Y is width of line
//z will be how far the collider reaches to the sky
lineCollider.size = new Vector3(lineLength, lineWidth, 1f);
// get the midPoint
Vector3 midPoint = (startPoint + endPoint) / 2;
// move the created collider to the midPoint
lineCollider.transform.position = midPoint;
//heres the beef of the function, Mathf.Atan2 wants the slope, be careful however because it wants it in a weird form
//it will divide for you so just plug in your (y2-y1),(x2,x1)
float angle = Mathf.Atan2((endPoint.z - startPoint.z), (endPoint.x - startPoint.x));
// angle now holds our answer but it's in radians, we want degrees
// Mathf.Rad2Deg is just a constant equal to 57.2958 that we multiply by to change radians to degrees
angle *= Mathf.Rad2Deg;
//were interested in the inverse so multiply by -1
angle *= -1;
// now apply the rotation to the collider's transform, carful where you put the angle variable
// in 3d space you don't wan't to rotate on your y axis
lineCollider.transform.Rotate(0, angle, 0);
}
Thanks for checking the tutorial out!!!
Heres the same thing with pictures: http://zackgrizzle.ninja/tutorials.html
Thank you. This method helped me. The line renderer, of same start and end width, got added with a new collider game object as child.
Answer by GLeBaTi · Oct 08, 2018 at 02:07 PM
You can use EdgeCollider:
var points = new List<Vector3>() { p1, p2, p3, p4 };
_lineRenderer.SetPositions(points.ToArray());
_edgeCollider.points = points.Select(x =>
{
var pos = _edgeCollider.transform.InverseTransformPoint(x);
return new Vector2(pos.x, pos.y);
}).ToArray();
Answer by bugz313 · Jul 07, 2017 at 06:18 PM
@Immanuel-Scholz You could try this: https://www.assetstore.unity3d.com/en/#!/content/32762