我想知道是否有从两个向量求圆心的公式。
例如,对于向量 (2,4) 和向量 (4,6),中心位置将是向量 (4,4)。这是我的问题的图片。
在图像中,我们可以看到圆上存在不同的向量,该公式的目的是仅从两点确定绿点的坐标。
我尝试了多种代码,但没有一个有效。
一些代码:
Vector3 direction = point1.forward.normalized;
Vector3 centerApproximation = (point1.position + point2.position) / 2f;
float distance = Vector3.Distance(point1.position, point2.position);
Vector3 orthoVector = Vector3.Cross(direction, Vector3.up);
Vector3 circleCenter = centerApproximation + orthoVector.normalized * Mathf.Sqrt((distance * distance) / 4 - Vector3.Dot(centerApproximation - point1.position, orthoVector.normalized));
// Trouver le point médian
Vector3 midpoint = (point1 + point2) / 2f;
// Calculer un vecteur perpendiculaire à la droite formée par les deux points
Vector3 direction = (point2 - point1).normalized;
Vector3 perpendicular = new Vector3(-direction.z, 0, direction.x); // Pour un plan 2D, si besoin
// Ajouter ce vecteur au point médian pour obtenir le troisième point
Vector3 thirdPoint = midpoint + perpendicular * (distance / 2f);```
我终于找到了解决办法。 这可能不是最好的,但现在就可以了。
对于第一点,我使用变换而不是向量来为圆心提供所需的方向。
从方向形成的直线中,我找到第三个向量,它是第二个向量和直线之间的对称性。 然后,使用这三个向量,计算圆心的位置。
这是执行此操作的代码草案:
{
[SerializeField] private Transform transform1;
[SerializeField] private Vector3 position2;
private void OnDrawGizmos()
{
if (transform1 == null || position2 == null)
return;
Gizmos.DrawSphere(transform1.position, 0.1f);
Gizmos.DrawLine(transform1.position, transform1.position + transform1.forward * 10f);
Gizmos.DrawSphere(position2, 0.1f);
Gizmos.color = Color.red;
Gizmos.DrawSphere(GetSymetricPosition(transform1, position2), 0.1f);
Gizmos.color = Color.green;
Gizmos.DrawSphere(GetCenterOfCircle(transform1.position, position2, GetSymetricPosition(transform1, position2)), 0.1f);
}
private Vector3 GetCenterOfCircle(Vector3 point1, Vector3 point2, Vector3 point3)
{
float x1 = point1.x;
float x2 = point2.x;
float x3 = point3.x;
float y1 = point1.z;
float y2 = point2.z;
float y3 = point3.z;
float x12 = x1 - x2;
float x13 = x1 - x3;
float y12 = y1 - y2;
float y13 = y1 - y3;
float y31 = y3 - y1;
float y21 = y2 - y1;
float x31 = x3 - x1;
float x21 = x2 - x1;
float sx13 = x1 * x1 - x3 * x3;
float sy13 = y1 * y1 - y3 * y3;
float sx21 = x2 * x2 - x1 * x1;
float sy21 = y2 * y2 - y1 * y1;
float f = ((sx13) * (x12) + (sy13) * (x12) + (sx21) * (x13) + (sy21) * (x13)) / (2 * ((y31) * (x12) - (y21) * (x13)));
float g = ((sx13) * (y12) + (sy13) * (y12) + (sx21) * (y13) + (sy21) * (y13)) / (2 * ((x31) * (y12) - (x21) * (y13)));
float c = -x1 * x1 - y1 * y1 - 2 * g * x1 - 2 * f * y1;
float h = -g;
float k = -f;
float sqr_of_r = h * h + k * k - c;
float r = Mathf.Sqrt(sqr_of_r);
Vector3 center = new Vector3(h, 0, k);
return center;
}
private Vector3 GetSymetricPosition(Transform transform1, Vector3 position2)
{
Vector3 direction = transform1.forward;
Vector3 intersectDirection = transform1.position + direction * Vector3.Dot(position2 - transform1.position, direction);
return intersectDirection + (intersectDirection - position2);
}
}```