Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As I said in a comment, it's <em>too hard to read</em>. While I'm not going to claim it's <em>the</em> problem (use a debugger as suggested by Mitch Wheat), it sure could be addressed!</p> <p>First, lets outline a collision detection for a single axis, X. Instead of looking first for a collision, let's look for <em>no collision</em>. There <em>isn't</em> a collision along the X axis [only] when "(player to left of enemy) or (enemy to left of player)". (Reason that if neither of these are true then "player on enemy" must be true - use pictures if needed.)</p> <p>Let p = Player, e = Enemy, then there is a <em>no collision</em> [only] when (p.X + p.W &lt; e.X) || (e.X + e.W &lt; p.X). This means that there <em>is</em> a collision in the opposite/negated case!</p> <p>Thus we can write the collision <em>method</em>:</p> <pre><code>bool Collides (IEntityBox p, IEntityBox e) { bool noCollisionX = (p.X + p.W &lt; e.X) || (e.X + e.W &lt; p.X); bool collisionX = !noCollisionX; bool noCollisionY = (p.Y + p.H &lt; e.Y) || (e.Y + e.H &lt; p.Y); bool collisionY = !noCollisionY; // not that the collision on BOTH axises must be fulfilled return collisionX &amp;&amp; collisionY; } </code></pre> <p>Notes (left as an exercise):</p> <ol> <li><p>IEntityBox has X/Y and W/H properties and (0,0) is assumed to the Top-Left corner of the screen. Use the the correct types/propeties for your implementation. It's simpler if the positioning is unified between the player and other entities.</p></li> <li><p>The expressions can be rewritten (and De Morgan's can be applied) to clean it up a little bit. Simple collapsing would eliminate all variables and yet keep it "easy" to read.</p></li> <li><p>If noCollisionX (which implies !collisionX) is true, we don't need to compute noCollisionY. This could either use an if/else or short-circuit evaluation if collapsed.</p></li> </ol> <p>Usage is likewise cleaned up:</p> <pre><code>bool PlayerCollidesWithAnyEnemy () { foreach (var e in enemies) { // avoid hard-coding numbers if (Collides(player, e)) { return true; } } return false; } // .. var playerOopsed = PlayerCollidesWithAnyEnemy(); </code></pre> <p>Or, with LINQ:</p> <pre><code>var playerOopsed = enemies.Any(e =&gt; Collides(player, e)); </code></pre>
    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. This table or related slice is empty.
    1. This table or related slice is empty.
    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