Skip to content

Instantly share code, notes, and snippets.

@SleeplessOwl0102
Last active July 4, 2023 12:00
Show Gist options
  • Save SleeplessOwl0102/e9f975ccd08aa0ea3b8ebe6aa33dd8e5 to your computer and use it in GitHub Desktop.
Save SleeplessOwl0102/e9f975ccd08aa0ea3b8ebe6aa33dd8e5 to your computer and use it in GitHub Desktop.
计算屏幕点击处,和3D空间中的线段,在屏幕空间中的最短距离
//计算屏幕点击处,和3D空间中的线段,在屏幕空间中的最短距离
public static float DetectClickOnLine(Camera camera,Vector3 p1, Vector3 p2)
{
var v1 = camera.WorldToScreenPoint(p1);
var v2 =camera.WorldToScreenPoint(p2);
Vector2 point = Input.mousePosition;
//计算点到直线的距离
var xDis = v2.x - v1.x;
var yDis = v2.y - v1.y;
var dx = point.x - v1.x;
var dy = point.y - v1.y;
var d = xDis * xDis + yDis * yDis;
var t = xDis * dx + yDis * dy;
if (d > 0)
t /= d;
if (t < 0)
t = 0;
else if (t > 1)
t = 1;
dx = v1.x + t * xDis - point.x;
dy = v1.y + t * yDis - point.y;
return Mathf.Sqrt(dx * dx + dy * dy);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment