刚好用到二维射线与直线相交,顺便记录一下。
问题如下:
二维平面中存在射线bp和直线ac,计算bp与ac的交点p1,计算原理很简单,通过直线方程组求解即可,如下:
将射线bp和直线ac的方程参数k1、k2、d1、d2计算出来,再计算二元一次方程组就能得到结果。
下面测试一下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayLineCross : MonoBehaviour
{
public Transform A;
public Transform B;
public Transform C;
public Transform P;
void Start()
{
}
void Update()
{
Vector2 a = A.position;
Vector2 b = B.position;
Vector2 c = C.position;
Vector2 p = P.position;
Vector2 p1 = GetRayLineCrossPoint(a, b, c, p);
#if UNITY_EDITOR
Debug.LogFormat("RayLineCross p1 = {0}", p1);
Debug.DrawLine(a, c, Color.white);
Debug.DrawLine(b, p, Color.white);
Debug.DrawLine(p, p1, Color.red);
#endif
}
private Vector2 GetRayLineCrossPoint(Vector2 a, Vector2 b, Vector2 c, Vector2 p)
{
float Xa = a.x, Ya = a.y, Xb = b.x, Yb = b.y, Xc = c.x, Yc = c.y, Xp = p.x, Yp = p.y;
float k1 = (Yp - Yb) / (Xp - Xb);
float d1 = Yb - k1 * Xb;
float k2 = (Yc - Ya) / (Xc - Xa);
float d2 = Ya - k2 * Xa;
float x = (d2 - d1) / (k1 - k2);
float y = k1 * x + d1;
return new Vector2(x, y);
}
}
效果如下:
计算正确,OK,有时间继续。