Mouse click on line - performance question

Hello everybody, I have a really specific question about the best practice in this case:

In my project you are drawing paths by clicking on other paths to chose the start point and use the mouse position as the end point.

Therefore I need to detect a mouse click on a path (line drawn with LineRenderer, consisting of one or two straight segments). Right now I’m looping through all the paths to check if the mouse position is closer to them than a detectionRadius I set.

My question is: Would it be better for the performance to give every path one BoxCollider2D
for each segment and detect a mouse hit by Raycasting, or is it okay as I do it now?
There will probably be 50 paths or more in the scene at some point.

Here is how it will look like:

48207-paths.png

Thanks for your answers!

For lines in 3D space, rather than Raycasting, you can render each line using a different color on a separate texture (see Render Texture). For example, render your first line using color 0x000000, your second line using 0x000001, etc. Here is an image example of what your render texture might look like for 3 lines.

48204-lines.png

This effectively projects all the lines onto the viewing plane, meaning that you can sample the color of the render texture at the screen-space mouse coordinates to see which line you’re over. In the image above, if your mouse is above a white pixel, you know it’s over the white line, etc. As a bonus, this also works for curves if you ever need to expand your system to support curves. (Curve intersection is a lot more difficult than line intersection.)

This saves you from raycasting and doing intersection tests, but in exchange, you have more draw calls. Although if you don’t care about the color of your lines, you can render them on to the screen normally, using different colors, and just see what color your mouse is over.

The same concept applies to lines in 2D space, but intersection tests in 2D are easier than intersection tests in 3D.