在JAVA中线和正方形的交点 [英] Intersection of line and square in JAVA

查看:111
本文介绍了在JAVA中线和正方形的交点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JAVA:



我正在研究一个网格,每个方格的中心点是一个整数坐标,我在两个整数之间画一条线并且需要检查它是否通过基于整数坐标的特定网格方块。



我看过类似的帖子/谷歌搜索结果,但是我的基本知识更多,所以我想知道是否有一个我无法理解的简单解决方案。 (最有可能)



欣赏您可以给予的任何帮助!

解决方案

我想你是问一个特定的线是否与一个特定的正方形相交(如果这个问题已经解决,它适用于任何数量的正方形)。

试试这个。假设这条线有方程y = a * x + b,并且方格左下角有
坐标(x1,y1),而左上角有坐标(x2,y2)。



找出点y'= a * x1 + b,y''= a * x2 + b(乘以*);

然后根据是否y'> y''或反之亦然,你有一个间隔[y',y'']或[y'',y'],比如对于间隔是[y', (在数学符号中,[m,n]代表所有数字> = m,并且<= n。)



如果[y',y'']与[y1,y2]相交,则线会进入方形。


JAVA:

I'm working on a grid where the centre point of each square is an integer co-ordinate and I'm drawing a line between two integers and need to check whether it goes through a specific grid square based around integer coordinates.

I've seen similar posts/google results but mine's a lot more basic so I'm wondering whether there's a simple solution I can't grasp. (Most probable)

Appreciate any help you can give!

解决方案

I think you are asking if one specific line intersects one specific square (if that problem is solved, it applies to any number of squares).

Try this. Say the line has equation y = a*x + b, and the lower left of the squares has coordinates (x1, y1) while the upper left corner has coordinates (x2, y2).

Find the points y' = a*x1 + b, y'' = a*x2 + b ("*" for multiply);

then depending on whether y' > y'' or vice versa, you have an intervals [y', y''] or [y'', y'], say for argument that the interval is [y', y''].

(In math notation, [m, n] stands for all numbers >= m, and <= n.)

If [y', y''] intersects [y1, y2], the line enters the square.

这篇关于在JAVA中线和正方形的交点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆