如何找到直线和矩形的交点

如何找到直线和矩形的交点

本文介绍了如何找到直线和矩形的交点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条从 A 点到 B 点的线;我有 (x,y) 两点.我还有一个以 B 为中心的矩形以及矩形的宽度和高度.

I have a line that goes from points A to B; I have (x,y) of both points. I also have a rectangle that's centered at B and the width and height of the rectangle.

我需要找到与矩形相交的直线中的点.有没有一个公式可以给我那个点的 (x,y)?

I need to find the point in the line that intersects the rectangle. Is there a formula that gives me the (x,y) of that point?

推荐答案

假设矩形是轴对齐的,这让事情变得非常简单:

Assuming the rectangle is axis-aligned, this makes things pretty simple:

直线的斜率是 s = (Ay - By)/(Ax - Bx).

The slope of the line is s = (Ay - By)/(Ax - Bx).

  • 如果 -h/2
  • 如果 Ax > Bx 则为右边缘
  • 如果 Ax < 则为左边缘Bx.
  • 如果 Ay > By 的顶边
  • 如果 Ay
  • 则为底边作者.

一旦你知道它相交的边,你就会知道一个坐标:x = Bx ± w/2 或 y = By ± h/2,具体取决于你碰到的边.另一个坐标由 y = By + s * w/2 或 x = Bx + (h/2)/s 给出.

Once you know the edge it intersects you know one coordinate: x = Bx ± w/2 or y = By ± h/2 depending on which edge you hit. The other coordinate is given by y = By + s * w/2 or x = Bx + (h/2)/s.

这篇关于如何找到直线和矩形的交点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:44