英文:
How do I add an on-click event to a line rendered with the LineRenderer component?
问题
实现带有点击功能的线渲染器
我是Unity的新手。我正在实现一个项目,需要根据坐标创建线条。我已经完成了这一部分,但我还需要能够点击该线条来执行脚本。我该如何实现这个功能?
英文:
Implement line renderer with click
I am new to Unity. I am implementing a project where I need to create lines based on coordinates. I have already done this, but I also have to be able to click on that line to execute a script. How can I achieve this?
答案1
得分: 2
这种行为不受默认的 LineRenderer
组件支持。
一种方法是根据用于绘制线的点来动态生成 2D Polygon Collider
。
您可以通过获取线的宽度,并确定指向下一个线点的方向向量来实现这一点。在每个点上,您将在'上'和'下'方向(即将垂直向量乘以'-1')中获取垂直方向,然后将这两个新点添加到您的Polygon Collider
中。仅使用两个线点,这将形成一个矩形的碰撞体。然后,您可以编写一个脚本,允许您从摄像机视图中使用 Raycasts
来“点击”该矩形。
请注意,2D Polygon Collider
可能要求这些点以特定顺序出现,这意味着您可能需要在整个线上“循环”,即首先从线的起点到终点获取所有正值的垂直值,然后获取所有负值的垂直值,从末尾开始并向起点移动。
还要注意,这种方法可能会在锐角处引起某些精度问题。如果您需要100%的精度,可能需要清理生成的点数据。
英文:
This behaviour is not supported by the default LineRenderer
component.
A way to do this would be to generate a 2D Polygon Collider
programmatically based on the points used to draw your line.
You could do this by taking the width of the line, and determining the directional vector towards the next line point. At each point, you would take the perpendicular direction from the directional vector in both the 'up' and 'down' (aka just multiply the perpendicular vector by -1
}, and then add those two new points to your Polygon Collider
. With just two line points, that would form a rectangular collider. You can then write a script that allows you to 'click' on that rectangle using Raycasts
from the Camera view.
Beware that the 2D Polygon Collider
may require those points to appear in a certain order, meaning that it is possible you'd have to 'loop around' your entire line, aka taking all the positive perpendicular values first, starting from the start of your line to the end of your line, and then all the negative perpendicular values, starting at the end and moving to the start.
Also beware that this method may cause certain accuracy issues at sharp corners. If you want 100% accuracy, you may have to clean up the resulting point data.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论