Unity中LineRenderer与EdgeCollider2D异常偏移问题求助
解决LineRenderer与EdgeCollider2D的偏移问题
问题原因
EdgeCollider2D的points属性使用局部坐标系,而你直接通过LineRenderer.GetPosition(i)获取的是世界坐标系坐标。当物体不在世界原点时,两种坐标系的差值会直接导致碰撞体与激光线出现偏移;只有在原点时两种坐标完全重合,所以功能表现正常。
修复代码
修改Laser_collision.cs,将LineRenderer的世界坐标转换为EdgeCollider2D所在物体的局部坐标后再赋值:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Laser_collision : MonoBehaviour { public LineRenderer lineRenderer; public EdgeCollider2D edgeCollider; void Update() { int pointCount = lineRenderer.positionCount; Vector2[] points = new Vector2[pointCount]; for(int i = 0; i < pointCount; i++) { // 将世界坐标转换为当前物体的局部坐标 Vector3 worldPos = lineRenderer.GetPosition(i); points[i] = transform.InverseTransformPoint(worldPos); } edgeCollider.points = points; } }
额外优化提示
- 变量名遵循C#小驼峰规范,避免与Unity内置API重名(比如把原代码中的
collider改为edgeCollider)。 - 可将Update中的逻辑移至LateUpdate,确保LineRenderer的位置更新完成后再同步碰撞体,避免帧同步问题。
- 原激光代码中的
m_transform可直接替换为内置的transform属性,无需单独赋值,减少冗余。
内容的提问来源于stack exchange,提问作者BOB
相关产品推荐
相关产品推荐

