Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The way I address this problem may not be optimal (in fact I'm sure it probably isn't) but it has worked for me in all my 2D platforming projects so far.</p> <p>I begin by defining a second rectangle for the sprite class. This rectangle will have the same Width and X coordinate as the main bounding box, but it will be slightly taller (in my case 2 or 3). You will also need to offset it so that the bottom edges of both rectangles are inline, to illustrate:</p> <pre><code>Rectangle boundingRect = new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height); Rectangle gravityRect = new Rectangle((int)boundingRect.X, (int)boundingRect.Y - 3, texture.Width, texture.Height + 3); </code></pre> <p>The sprite class also needs a bool to keep track of if the player should be falling. And one to keep track of whether it is solid (which you obviously assign as desired, during initialization).</p> <pre><code>public bool isGrounded = false; bool isSolid; </code></pre> <p>At the top of my Game1 class, I declare 2 ints:</p> <pre><code>int gravityTotalI = 0; int gravityCounterI = 0; </code></pre> <p>When initializing my sprites, I usually add them all to a List. So that I can do this:</p> <pre><code>foreach (Sprite s in spriteList) { if (s.isSolid) { gravityTotalI++; } } </code></pre> <p>Now, I use this bit of logic in the Game1 Update Method:</p> <pre><code>foreach (Sprite s in spriteList) { if (!s.Equals(player) { if (player.boundingRect.Intersects(s.boundingRect) || player.boundingRect.Intersects(s.gravityRect)) { player.isGrounded = true; gravityCounterI = 0; } else { gravCounterI++; if (gravCounterI &gt;= gravTotalI) { player.isGrounded = false; gravCounterI = 0; } } if (player.boundingRect.Intersects(s.boundingRect)) { player.position.Y -= 2f; //set the resistance of the platform here } } } //end of foreach loop. if (!player.isGrounded) { player.position.Y += 2f; //set the force of gravity here. } </code></pre> <p>Building a decent directional collision engine is a different thing, but this technique will handle the basics (and get rid of that infernal bouncing).</p> <p>Hope this isn't too long-winded/doesn't miss out anything important, and I really hope it helps - I struggled with exactly the same problem as you for a long time, and I know how frustrating it can be!</p> <p>I'm looking forward to seeing others' techniques for handling this!</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