MBo 的想法是正确的。这是在 Unity 中实现的一种方法。我认为 UnityScript 不值得使用——尤其是它不支持扩展方法——所以你真的应该切换语言。(另外,Unity 实际上并没有命名为 Unity3D。)
这个脚本可以在项目中的任何地方:
using UnityEngine;
public static class UnityEngineExtensions {
public static Vector2 Abs(this Vector2 vector) {
for (int i = 0; i < 2; ++i) vector[i] = Mathf.Abs(vector[i]);
return vector;
}
public static Vector2 DividedBy(this Vector2 vector, Vector2 divisor) {
for (int i = 0; i < 2; ++i) vector[i] /= divisor[i];
return vector;
}
public static Vector2 Max(this Rect rect) {
return new Vector2(rect.xMax, rect.yMax);
}
public static Vector2 IntersectionWithRayFromCenter(this Rect rect, Vector2 pointOnRay) {
Vector2 pointOnRay_local = pointOnRay - rect.center;
Vector2 edgeToRayRatios = (rect.Max() - rect.center).DividedBy(pointOnRay_local.Abs());
return (edgeToRayRatios.x < edgeToRayRatios.y) ?
new Vector2(pointOnRay_local.x > 0 ? rect.xMax : rect.xMin,
pointOnRay_local.y * edgeToRayRatios.x + rect.center.y) :
new Vector2(pointOnRay_local.x * edgeToRayRatios.y + rect.center.x,
pointOnRay_local.y > 0 ? rect.yMax : rect.yMin);
}
}
将此其他脚本附加到游戏对象,并在检查器中设置其变量。
#pragma warning disable 0649
using System;
using UnityEngine;
public class VisualizeRectIntersectionWithRayFromCenter : MonoBehaviour {
[SerializeField] Rect rect;
[SerializeField] Vector2 point;
[Serializable] class Colors {
public Color rect, point, intersection;
} [SerializeField] Colors colors;
void OnDrawGizmos() {
Gizmos.color = colors.rect;
Vector2[] corners = {new Vector2(rect.xMin, rect.yMin), new Vector2(rect.xMin, rect.yMax),
rect.Max(), new Vector2(rect.xMax, rect.yMin)};
int i = 0;
while (i < 3) Gizmos.DrawLine(corners[i], corners[++i]);
Gizmos.DrawLine(corners[3], corners[0]);
Gizmos.color = colors.point;
Gizmos.DrawLine(rect.center, point);
Gizmos.color = colors.intersection;
Gizmos.DrawLine(rect.center, rect.IntersectionWithRayFromCenter(pointOnRay: point));
}
}