如何计算从正方形表面上给定点到任意给定方向的边缘的距离? [英] How to calculate the distance from a given point on the surface of a square to its edge with any given direction?
问题描述
我试图找出从点到正方形表面边缘的距离(无论其方向角度如何).我已经附上了我所谈论的内容的粗略图.
I am trying to figure out what the distance is from a point to the edge of a square's surface (regardless of its angle of direction). I've attached a rough drawing of what I'm talking about.
网格以正方形为中心(尽管绘制不佳).从正方形中心到圆心的距离.我希望找到一种方法来计算圆与正方形的边缘之间的距离,而不管它朝向哪个方向,而不必在我的代码中使用很多if-else语句.
The grid is centered around the square (although poorly drawn). The distance from the center of the square to the center of the circle. I was hoping to find a way to calculate the distance to the edge of the square from the circle no matter which direction it is headed without having to use a lot of if-else statements in my code.
如果您有什么好主意,请告诉我!
Let me know if you have any nice ideas!
推荐答案
据我了解,您定义了坐标和方向,并希望找到相交的边缘点.建立沿两个坐标移动的方程式,并计算相交的第一次时间.没有if就没有魔术方法
As far as I understand, you define coordinates and direction and want to find intersection edge point. Make equations for moving along both coordinates and calculate the first time of intersection. There is no magic way without if's
vx = Cos(Direction)
vy = Sin(Direction)
x = x0 + vx * t
y = y0 + vy * t
//potential border positions
if vx > 0 then
ex = x2
else
ex = x1
if vy > 0 then
ey = y2
else
ey = y1
//check for horizontal/vertical directions
if vx = 0 then
return cx = x0, cy = ey
if vy = 0 then
return cx = ex, cy = y0
//in general case find times of intersections with horizontal and vertical edge line
tx = (ex - x0) / vx
ty = (ey - y0) / vy
//and get intersection for smaller parameter value
if tx <= ty then
return cx = ex, cy = y0 + tx * vy
else
return cx = x0 + ty * vx, cy = ey
这篇关于如何计算从正方形表面上给定点到任意给定方向的边缘的距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!