我如何看到两个矩形在JavaScript还是伪代码中相交? [英] How do I see if two rectangles intersect in javascript or pseudocode?

查看:144
本文介绍了我如何看到两个矩形在JavaScript还是伪代码中相交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



它们由[x0,y0,x1,y1]对表示,它们由[x0,y0,x1,y1]表示矩形的左上角和右下角。或者你的解决方案可能是[x0,y0,宽度,高度],如果它更简单一些,我可以调整我的函数的参数输入。



我试着看看是否有从矩形A的两个角落包含在矩形B中,但是如果A大于B并且B部分包含在A中,则它将表示它不重叠。现在我可以尝试A和B,但这似乎是一种不好的方式去做事情。



我无法预先制作一个大网格,并通过矩形占据单元格,因为它不知道矩形是什么。我所能说的是,它们是无符号整数,最小值为0,最大值未知。

解决方案

检查矩形绝对不是相交的。如果没有这些情况是真的,那么矩形必须相交。即:

  public boolean rectanglesIntersect(
float minAx,float minAy,float maxAx,float maxAy,
float minBx,float minBy,float maxBx,float maxBy){
boolean aLeftOfB = maxAx< minBx;
boolean aRightOfB = minAx> maxBx;
boolean aAboveB = minAy> maxBy;
boolean aBelowB = maxAy< minBy;

return!(aLeftOfB || aRightOfB || aAoveb || aBelowB);
}

这说明了这个概念,但是可以通过内联布尔以利用 ||


的短路行为

I have two rectangles which I must return in a function whether they intersect or not.

They are represented by [ x0,y0, x1,y1 ] pairs that represent the top-left and bottom-right corner of the rectangles. Alternatively your solution could be [ x0, y0, width, height ] if its somehow simpler, I can adapt my function's parameter input by it.

I tried to see if any of the two corners from rectangle A are included in rectangle B but if A is larger than B and B is partially included in A, it will say it doesn't overlap. Now I could try A and B but this seems to be a bad way to do things.

I can't premake a big grid and occupy cells by the rectangles because it is unknown what rectangles come as. All I can tell is that they are unsigned integers, min 0 and with unknown max.

解决方案

Check for the cases where the rectangles are definitely not intersecting. If none of these cases are true then the rectangles must intersect. i.e.:

public boolean rectanglesIntersect( 
      float minAx, float minAy, float maxAx, float maxAy,
      float minBx, float minBy, float maxBx, float maxBy ) {
    boolean aLeftOfB = maxAx < minBx;
    boolean aRightOfB = minAx > maxBx;
    boolean aAboveB = minAy > maxBy;
    boolean aBelowB = maxAy < minBy;

    return !( aLeftOfB || aRightOfB || aAboveB || aBelowB );
}

This illustrates the concept, but could be made slightly faster by inlining the booleans so as to take advantage of the short-circuiting behaviour of ||

这篇关于我如何看到两个矩形在JavaScript还是伪代码中相交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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