我正在使用来自 UnityCommunity Github 的 此代码 在屏幕边框周围创建边缘碰撞器:
public class ScreenEdgeColliders : MonoBehaviour
{
private Camera cam;
private EdgeCollider2D edge;
private Vector2[] edgePoints;
void Awake()
{
if (Camera.main == null) Debug.LogError("Camera.main not found, failed to create edge colliders");
else cam = Camera.main;
if (!cam.orthographic) Debug.LogError("Camera.main is not Orthographic, failed to create edge colliders");
// add or use existing EdgeCollider2D
edge = GetComponent<EdgeCollider2D>() == null ? gameObject.AddComponent<EdgeCollider2D>() : GetComponent<EdgeCollider2D>();
edgePoints = new Vector2[5];
AddCollider();
}
//Use this if you're okay with using the global fields and code in Awake() (more efficient)
//You can just ignore/delete StandaloneAddCollider() if thats the case
void AddCollider()
{
//Vector2's for the corners of the screen
Vector2 bottomLeft = cam.ScreenToWorldPoint(new Vector3(0, 0, cam.nearClipPlane));
Vector2 topRight = cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, cam.pixelHeight, cam.nearClipPlane));
Vector2 topLeft = new Vector2(bottomLeft.x, topRight.y);
Vector2 bottomRight = new Vector2(topRight.x, bottomLeft.y);
//Update Vector2 array for edge collider
edgePoints[0] = bottomLeft;
edgePoints[1] = topLeft;
edgePoints[2] = topRight;
edgePoints[3] = bottomRight;
edgePoints[4] = bottomLeft;
edge.points = edgePoints;
}
}
我将此脚本附加到我的主相机上。它运作得很好。物体被围住并且通常会从墙壁上反弹。问题是物体有时会卡在这些碰撞器中,我无法将它们拖离墙壁。我可以在这段代码中添加什么来确保对象不会卡住吗?
这更多是 Unity 的问题,而不是脚本的问题。尝试一下
Extrapolate
。FixedUpdate
而不是更新。这通常对我有用。