Bouncing off the walls: This is about colliding with the sides of the viewport

We all bounce off the walls from time to time, here is some code without explanation on how to do so.  You will need a really simple png image to make this happen, or even a real complex one.

You will need a small png to do this app, I have attached the working code at the end of the article.

For your game class, replace all of the code with the first block and then below it is the ball class (make sure to scroll down to get the code for the ball class below the first code block):

Code Snippet

  1. sing System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Microsoft.Xna.Framework;
  5. using Microsoft.Xna.Framework.Audio;
  6. using Microsoft.Xna.Framework.Content;
  7. using Microsoft.Xna.Framework.GamerServices;
  8. using Microsoft.Xna.Framework.Graphics;
  9. using Microsoft.Xna.Framework.Input;
  10. using Microsoft.Xna.Framework.Input.Touch;
  11. using Microsoft.Xna.Framework.Media;
  12.  
  13. namespace PhonePong
  14. {
  15.     /// <summary>
  16.     /// This is the main type for your game
  17.     /// </summary>
  18.     public class Game1 : Microsoft.Xna.Framework.Game
  19.     {
  20.         GraphicsDeviceManager graphics;
  21.         SpriteBatch spriteBatch;
  22.         Texture2D t_ball;
  23.         Rectangle r_ball;
  24.         Boolean b_viewportleft=false,       //grouping booleans all in
  25.                 b_viewportright= false,     //the same area
  26.                 b_viewporttop = false,
  27.                 b_viewportbottom = false;
  28.  
  29.         
  30.         Ball ball;
  31.  
  32.         /**********************************************
  33.          * For tracking ball process
  34.          * https://msdn.microsoft.com/en-us/library/bb447673.aspx
  35.          * *******************************************/
  36.         SpriteFont Font1;
  37.         Vector2 FontPosX, FontPosY;
  38.  
  39.         Random rand = new Random();     
  40.         
  41.         public Game1()
  42.         {
  43.             graphics = new GraphicsDeviceManager(this);
  44.             Content.RootDirectory = "Content";
  45.  
  46.             // Frame rate is 30 fps by default for Windows Phone.
  47.             TargetElapsedTime = TimeSpan.FromTicks(333333);
  48.  
  49.             // Extend battery life under lock.
  50.             InactiveSleepTime = TimeSpan.FromSeconds(1);
  51.         }
  52.  
  53.         /// <summary>
  54.         /// Allows the game to perform any initialization it needs to before starting to run.
  55.         /// This is where it can query for any required services and load any non-graphic
  56.         /// related content. Calling base.Initialize will enumerate through any components
  57.         /// and initialize them as well.
  58.         /// </summary>
  59.         protected override void Initialize()
  60.         {
  61.             // TODO: Add your initialization logic here
  62.             
  63.             ResetGame();
  64.             r_ball = new Rectangle(ball.pos.X, ball.pos.Y, 50, 50);
  65.            
  66.             base.Initialize();
  67.         }
  68.         void ResetGame()
  69.         {
  70.              ball = new Ball(385, 285);
  71.         }
  72.  
  73.  
  74.         void UpdateBall()
  75.         {
  76.             //update positions
  77.             r_ball.X += ball.h_speed;
  78.             r_ball.Y += ball.v_speed;
  79.             
  80.  
  81.             //check for boundaries
  82.             //bottom
  83.             if (r_ball.Y >
  84.                 graphics.GraphicsDevice.Viewport.Height - r_ball.Height)
  85.             {
  86.                 b_viewportbottom = !b_viewportbottom;
  87.                 ball.v_speed *= -1;
  88.             }               
  89.             
  90.             //top
  91.             if (r_ball.Y < 0)
  92.             {
  93.                 b_viewporttop = !b_viewporttop;
  94.                 ball.v_speed *= -1;
  95.             }
  96.             //Left
  97.             if (r_ball.X >
  98.                 graphics.GraphicsDevice.Viewport.Width - r_ball.Width)
  99.             {
  100.                 b_viewportleft = !b_viewportleft;
  101.                 ball.h_speed *= -1;
  102.             }
  103.             //right
  104.             if (r_ball.X < 0)
  105.             {
  106.                 b_viewportright = !b_viewportright;
  107.                 ball.h_speed *= -1;
  108.             }
  109.         }
  110.                 
  111.  
  112.                 
  113.  
  114.         /// <summary>
  115.         /// LoadContent will be called once per game and is the place to load
  116.         /// all of your content.
  117.         /// </summary>
  118.         protected override void LoadContent()
  119.         {
  120.             // Create a new SpriteBatch, which can be used to draw textures.
  121.             spriteBatch = new SpriteBatch(GraphicsDevice);
  122.             t_ball = Content.Load<Texture2D>("ball");
  123.  
  124.             /***************************************************
  125.              * For tracking the ball position
  126.              * https://msdn.microsoft.com/en-us/library/bb447673.aspx
  127.              * ************************************************/
  128.             Font1 = Content.Load<SpriteFont>("SpriteFont1");
  129.             FontPosY = new Vector2(10, 10);
  130.             FontPosX = new Vector2(10, 100);
  131.             /****************************************************
  132.              ***************************************************/
  133.  
  134.         }
  135.  
  136.  
  137.         protected override void Update(GameTime gameTime)
  138.         {
  139.             UpdateBall();        
  140.  
  141.             base.Update(gameTime);
  142.         }
  143.  
  144.         /// <summary>
  145.         /// This is called when the game should draw itself.
  146.         /// </summary>
  147.         /// <param name="gameTime">Provides a snapshot of timing values.</param>
  148.         protected override void Draw(GameTime gameTime)
  149.         {
  150.             
  151.             
  152.             
  153.             if (b_viewportbottom)
  154.             {
  155.                 GraphicsDevice.Clear(Color.Yellow);
  156.             }
  157.             else
  158.             {
  159.                 GraphicsDevice.Clear(Color.DodgerBlue);
  160.             }
  161.             spriteBatch.Begin();
  162.  
  163.             spriteBatch.Draw(t_ball, r_ball, Color.Red);
  164.             /*****************************************************
  165.              * Refactor Code starts here (start paste after
  166.              * the line of asteriks or stars)
  167.              *****************************************************/
  168.             String ViewportWidth;
  169.             String BallY;
  170.             StringMethod(out ViewportWidth, out BallY);
  171.             /*****************************************************
  172.              * Refactor code finishes here (End paste at the line
  173.              * above the line of asteriks or stars)
  174.              * **************************************************/
  175.             spriteBatch.DrawString(Font1,
  176.                                     ViewportWidth,
  177.                                     FontPosX,
  178.                                     Color.Yellow);
  179.             spriteBatch.DrawString(Font1,
  180.                                     BallY,
  181.                                     FontPosY,
  182.                                     Color.Black);
  183.             spriteBatch.End();           
  184.                 
  185.             base.Draw(gameTime);
  186.         }
  187.  
  188.         private void StringMethod(out String ViewportWidth, out String BallY)
  189.         {
  190.             String ViewportHeight =
  191.                             Convert.ToString(graphics.GraphicsDevice.Viewport.Bounds.Height);
  192.             ViewportWidth =
  193.                 Convert.ToString(graphics.GraphicsDevice.Viewport.Width);
  194.             String ViewportData =
  195.                 "Height =" + ViewportHeight + " Width = " + ViewportWidth;
  196.             BallY =
  197. "Y= " + Convert.ToString(r_ball.Y); //Y= is a string
  198.             String BallX =
  199.                 "X= " + Convert.ToString(r_ball.X); //X= is a string
  200.         }
  201.  
  202.    
  203.     }
  204. }

Now create a class named ball.cs and cut and paste the following to the class code:

Code Snippet

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Microsoft.Xna.Framework;
  5. using Microsoft.Xna.Framework.Audio;
  6. using Microsoft.Xna.Framework.Content;
  7. using Microsoft.Xna.Framework.GamerServices;
  8. using Microsoft.Xna.Framework.Graphics;
  9. using Microsoft.Xna.Framework.Input;
  10. using Microsoft.Xna.Framework.Input.Touch;
  11. using Microsoft.Xna.Framework.Media;
  12.  
  13.  
  14. namespace PhonePong
  15. {
  16.  
  17.     class Ball
  18.     {
  19.         //Don't forget to fix the usings
  20.         //position of ball
  21.         public Point pos;
  22.         public int h_speed, v_speed;
  23.  
  24.         //constructor - position
  25.         public Ball(int x, int y)
  26.         {
  27.             pos = new Point(x, y);
  28.  
  29.             Random rand = new Random();
  30.             h_speed = rand.Next(3, 7);
  31.             //h_speed = 1;
  32.  
  33.             if (rand.Next(0, 2) == 0) h_speed *= -1;
  34.  
  35.             rand = new Random();
  36.             v_speed = rand.Next(3, 7);
  37.             //v_speed = 1;
  38.             if (rand.Next(0, 2) == 0) v_speed *= -1;
  39.         }
  40.     }
  41.                 
  42. }

PhonePong.zip