Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You only need to check the <em>edges</em> of the bounding box. Some pseudo code could look like.</p> <pre><code>if Rect1[RIGHT] &lt; Rect2[LEFT] or Rect1[LEFT] &gt; Rect2[RIGHT] or Rect1[TOP] &lt; Rect2[BOTTOM] or Rect1[BOTTOM] &gt; Rect2[TOP] then return false else return true </code></pre> <p>What this is trying to say is that if there are any possible gaps along the X or Y coordinate system separating the boxes then a collision is not possible. This is a <em>very</em> simple version of the <a href="http://www.codezealot.org/archives/55" rel="noreferrer">SAT (Separating Axis Theorem)</a> </p> <p>A little image of what this looks like visually, the same idea is applied here also.</p> <p><img src="https://i.stack.imgur.com/eSdbx.png" alt="Visualisation of SAT"></p> <p>This should mean that something similar to the following should work. Please note I haven't testing it but could lead you in the right direction.</p> <pre><code>public boolean collidesWith(ICollider otherObj) { GameObject gObj = (GameObject) otherObj; //this collider int r1 = (int) (getX() + getWidth()/2); int l1 = (int) (getX() - getWidth()/2); int t1 = (int) (getY() + getHeight()/2); int b1 = (int) (getY() - getHeight()/2); //the other collider int r2 = (int) (gObj.getX() + gObj.getWidth()/2); int l2 = (int) (gObj.getX() - gObj.getWidth()/2); int t2 = (int) (gObj.getY() + gObj.getHeight()/2); int b2 = (int) (gObj.getY() - gObj.getHeight()/2); if (r1 &lt; l2 || l1 &gt; r2 || t1 &lt; b2 || b1 &gt; t2) return false; else return true; /* Or could be shortened down to return !(r1 &lt; l2 || l1 &gt; r2 || t1 &lt; b2 || b1 &gt; t2) */ } </code></pre> <p>quite a reduction in code wont you say ;)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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