Note that there are some explanatory texts on larger screens.

plurals
  1. POBest way to move a rectangle in XNA/C#
    text
    copied!<p>I'm a starter in XNA and I'm trying to make a pong-game.<br> I've been able to make a pong game, but all the code was in one class. So I wanted to try to add a little bit of OOP and I've made a class for the ball and one for the pad.</p> <p>The ball moves perfectly, but I don't seem to able to make the ball bounce from the pads. </p> <p>These are the codes I use:<br> <strong>To move the pads</strong><br> <em>Game1.cs</em></p> <pre><code>#region left if (_KBS.IsKeyDown(Keys.W) || _KBS.IsKeyDown(Keys.Z)) Left.MoveUp(); else if (_KBS.IsKeyDown(Keys.S)) Left.MoveDown(); #endregion #region right if (_KBS.IsKeyDown(Keys.Up)) Right.MoveUp(); else if (_KBS.IsKeyDown(Keys.Down)) Right.MoveDown(); #endregion </code></pre> <p><em>pad.cs</em></p> <pre><code>public void MoveUp() { if (!paused) RecPad.Offset(0, -speed); CheckBorders(); } public void MoveDown() { if (!paused) RecPad.Offset(0, speed); CheckBorders(); } private void CheckBorders() { MathHelper.Clamp(recPad.Y, borders.Top, borders.Bottom - recPad.Height); } </code></pre> <p><strong>To check if the ball bounces</strong><br> <em>ball.cs</em></p> <pre><code>public void CheckBounce() { if ((myBounds.Intersects(left) &amp;&amp; movement.X &lt; 0) || (myBounds.Intersects(right) &amp;&amp; movement.X &gt; 0)) movement.X *= -1; } public void Draw(SpriteBatch sBatch, Texture2D texture, Color color, Rectangle left, Rectangle right) { this.left = left; this.right = right; Move(); sBatch.Begin(); sBatch.Draw(texture, myBounds, color); sBatch.End(); } </code></pre> <p><em>pad.cs</em></p> <pre><code>public Rectangle RecPad { get { return recPad; } private set { recPad = value; } } </code></pre> <p><em>Game1.cs</em></p> <pre><code>Ball.Draw(spriteBatch, ball, Color.White, Left.RecPad, Right.RecPad); </code></pre> <p><strong>I seemed to get the pads back to work</strong><br> The problem seems to be solved by using the originel recPad instead of the constructor RecPad<br> Now I only need to get my boundries working, because the MathHelper.Clamp doesn't seem to work<br> See <a href="http://pastebin.com/DgquAJbk" rel="nofollow">my code</a> for more info</p> <p>This code now fixed my border-problem</p> <pre><code>private void CheckBorders() { if (recPad.Top &lt; borders.Top) recPad.Location = new Point(recPad.X, borders.Top); if (recPad.Bottom &gt; borders.Bottom) recPad.Location = new Point(recPad.X, borders.Bottom - recPad.Height); } </code></pre>
 

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