Note that there are some explanatory texts on larger screens.

plurals
  1. POFinding out if two rectangles intersect
    text
    copied!<p>This is a homework assignment, so I'm mostly asking for a nudge in the right direction. I've figured out the majority of the problem. We have a Rectangle class, whose rectangles are defined by the x and y coordinates in a Point class. The one part I'm stuck on is figuring out if the two rectangles intersect. I've done some research, and came upon this:</p> <p><a href="http://silentmatt.com/rectangle-intersection/" rel="nofollow">http://silentmatt.com/rectangle-intersection/</a></p> <p>That helps me with how it would need to be done. But I can't seem to implement it in the way that our teacher had it setup in the problem overview:</p> <pre><code>//This method returns true if this rectangle intersects with another rectangle (which is provided as a parameter) bool intersects(Rectangle); </code></pre> <p>The intersects function only takes one parameter, that is of the Rectangle class. The call to it in main is something like this:</p> <pre><code>rec1.intersects(rec2); </code></pre> <p>I can't seem to figure out how to implement the actual function, though. I've already defined the points for both rec1 and rec2 with setters, but I can't seem to figure out how to access those points with the function that only accepts the one parameter. Because, in the example above, I can access the x and y points for rec2, but I can't with rec1.</p> <p>Any tips on how to proceed?</p> <p>EDIT: I think part of my problem is just how this was implemented. Here's what we have in the Rectangle class:</p> <pre><code>private: Point lowerLeftCorner; Point upperRightCorner; </code></pre> <p>And then he had us setup get and set functions in the Point class to set the points for lowerLeftCorner and upperRightCorner.</p> <p>The problem is when I'm in the intersect function, I can ONLY (unless I'm missing something) use the get functions for the parameter (rectangle2) and not for the first rectangle (rectangle1).</p> <p>If I was able to pass both rectangles as parameters, I could use the given examples to solve this. It's being able to find the values of x and y for the first rectangle that's giving me trouble.</p> <p>EDIT: Robert's info helped me figure out how to do it using "this". Here's what I ended up with which seems to work well. It's probably not the best, I am still pretty new to programming.</p> <pre><code>bool Rectangle::intersects(Rectangle rec2) { return ( getupperX() &gt; rec2.getlowerX() &amp;&amp; getlowerX() &lt; rec2.getupperX() &amp;&amp; getupperY() &gt; rec2.getlowerY() &amp;&amp; getlowerY() &lt; rec2.getupperY()); } } </code></pre> <p>Seems to have worked for all the values I've tested!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload