Last active
July 4, 2023 12:00
-
-
Save SleeplessOwl0102/e9f975ccd08aa0ea3b8ebe6aa33dd8e5 to your computer and use it in GitHub Desktop.
计算屏幕点击处,和3D空间中的线段,在屏幕空间中的最短距离
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //计算屏幕点击处,和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