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
- sing System;
- using System.Collections.Generic;
- using System.Linq;
- using Microsoft.Xna.Framework;
- using Microsoft.Xna.Framework.Audio;
- using Microsoft.Xna.Framework.Content;
- using Microsoft.Xna.Framework.GamerServices;
- using Microsoft.Xna.Framework.Graphics;
- using Microsoft.Xna.Framework.Input;
- using Microsoft.Xna.Framework.Input.Touch;
- using Microsoft.Xna.Framework.Media;
- namespace PhonePong
- {
- /// <summary>
- /// This is the main type for your game
- /// </summary>
- public class Game1 : Microsoft.Xna.Framework.Game
- {
- GraphicsDeviceManager graphics;
- SpriteBatch spriteBatch;
- Texture2D t_ball;
- Rectangle r_ball;
- Boolean b_viewportleft=false, //grouping booleans all in
- b_viewportright= false, //the same area
- b_viewporttop = false,
- b_viewportbottom = false;
- Ball ball;
- /**********************************************
- * For tracking ball process
- * https://msdn.microsoft.com/en-us/library/bb447673.aspx
- * *******************************************/
- SpriteFont Font1;
- Vector2 FontPosX, FontPosY;
- Random rand = new Random();
- public Game1()
- {
- graphics = new GraphicsDeviceManager(this);
- Content.RootDirectory = "Content";
- // Frame rate is 30 fps by default for Windows Phone.
- TargetElapsedTime = TimeSpan.FromTicks(333333);
- // Extend battery life under lock.
- InactiveSleepTime = TimeSpan.FromSeconds(1);
- }
- /// <summary>
- /// Allows the game to perform any initialization it needs to before starting to run.
- /// This is where it can query for any required services and load any non-graphic
- /// related content. Calling base.Initialize will enumerate through any components
- /// and initialize them as well.
- /// </summary>
- protected override void Initialize()
- {
- // TODO: Add your initialization logic here
- ResetGame();
- r_ball = new Rectangle(ball.pos.X, ball.pos.Y, 50, 50);
- base.Initialize();
- }
- void ResetGame()
- {
- ball = new Ball(385, 285);
- }
- void UpdateBall()
- {
- //update positions
- r_ball.X += ball.h_speed;
- r_ball.Y += ball.v_speed;
- //check for boundaries
- //bottom
- if (r_ball.Y >
- graphics.GraphicsDevice.Viewport.Height - r_ball.Height)
- {
- b_viewportbottom = !b_viewportbottom;
- ball.v_speed *= -1;
- }
- //top
- if (r_ball.Y < 0)
- {
- b_viewporttop = !b_viewporttop;
- ball.v_speed *= -1;
- }
- //Left
- if (r_ball.X >
- graphics.GraphicsDevice.Viewport.Width - r_ball.Width)
- {
- b_viewportleft = !b_viewportleft;
- ball.h_speed *= -1;
- }
- //right
- if (r_ball.X < 0)
- {
- b_viewportright = !b_viewportright;
- ball.h_speed *= -1;
- }
- }
- /// <summary>
- /// LoadContent will be called once per game and is the place to load
- /// all of your content.
- /// </summary>
- protected override void LoadContent()
- {
- // Create a new SpriteBatch, which can be used to draw textures.
- spriteBatch = new SpriteBatch(GraphicsDevice);
- t_ball = Content.Load<Texture2D>("ball");
- /***************************************************
- * For tracking the ball position
- * https://msdn.microsoft.com/en-us/library/bb447673.aspx
- * ************************************************/
- Font1 = Content.Load<SpriteFont>("SpriteFont1");
- FontPosY = new Vector2(10, 10);
- FontPosX = new Vector2(10, 100);
- /****************************************************
- ***************************************************/
- }
- protected override void Update(GameTime gameTime)
- {
- UpdateBall();
- base.Update(gameTime);
- }
- /// <summary>
- /// This is called when the game should draw itself.
- /// </summary>
- /// <param name="gameTime">Provides a snapshot of timing values.</param>
- protected override void Draw(GameTime gameTime)
- {
- if (b_viewportbottom)
- {
- GraphicsDevice.Clear(Color.Yellow);
- }
- else
- {
- GraphicsDevice.Clear(Color.DodgerBlue);
- }
- spriteBatch.Begin();
- spriteBatch.Draw(t_ball, r_ball, Color.Red);
- /*****************************************************
- * Refactor Code starts here (start paste after
- * the line of asteriks or stars)
- *****************************************************/
- String ViewportWidth;
- String BallY;
- StringMethod(out ViewportWidth, out BallY);
- /*****************************************************
- * Refactor code finishes here (End paste at the line
- * above the line of asteriks or stars)
- * **************************************************/
- spriteBatch.DrawString(Font1,
- ViewportWidth,
- FontPosX,
- Color.Yellow);
- spriteBatch.DrawString(Font1,
- BallY,
- FontPosY,
- Color.Black);
- spriteBatch.End();
- base.Draw(gameTime);
- }
- private void StringMethod(out String ViewportWidth, out String BallY)
- {
- String ViewportHeight =
- Convert.ToString(graphics.GraphicsDevice.Viewport.Bounds.Height);
- ViewportWidth =
- Convert.ToString(graphics.GraphicsDevice.Viewport.Width);
- String ViewportData =
- "Height =" + ViewportHeight + " Width = " + ViewportWidth;
- BallY =
- "Y= " + Convert.ToString(r_ball.Y); //Y= is a string
- String BallX =
- "X= " + Convert.ToString(r_ball.X); //X= is a string
- }
- }
- }
Now create a class named ball.cs and cut and paste the following to the class code:
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using Microsoft.Xna.Framework;
- using Microsoft.Xna.Framework.Audio;
- using Microsoft.Xna.Framework.Content;
- using Microsoft.Xna.Framework.GamerServices;
- using Microsoft.Xna.Framework.Graphics;
- using Microsoft.Xna.Framework.Input;
- using Microsoft.Xna.Framework.Input.Touch;
- using Microsoft.Xna.Framework.Media;
- namespace PhonePong
- {
- class Ball
- {
- //Don't forget to fix the usings
- //position of ball
- public Point pos;
- public int h_speed, v_speed;
- //constructor - position
- public Ball(int x, int y)
- {
- pos = new Point(x, y);
- Random rand = new Random();
- h_speed = rand.Next(3, 7);
- //h_speed = 1;
- if (rand.Next(0, 2) == 0) h_speed *= -1;
- rand = new Random();
- v_speed = rand.Next(3, 7);
- //v_speed = 1;
- if (rand.Next(0, 2) == 0) v_speed *= -1;
- }
- }
- }