Game1.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // Game.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. #region Using Statements
  10. using System;
  11. using System.Collections.Generic;
  12. using Microsoft.Xna.Framework;
  13. using Microsoft.Xna.Framework.Audio;
  14. using Microsoft.Xna.Framework.Content;
  15. using Microsoft.Xna.Framework.Graphics;
  16. using Microsoft.Xna.Framework.Input;
  17. using Microsoft.Xna.Framework.Storage;
  18. #endregion
  19. namespace PerPixelCollision
  20. {
  21. /// <summary>
  22. /// This is the main type for your game
  23. /// </summary>
  24. public class PerPixelCollisionGame : Microsoft.Xna.Framework.Game
  25. {
  26. GraphicsDeviceManager graphics;
  27. // The images we will draw
  28. Texture2D personTexture;
  29. Texture2D blockTexture;
  30. // The color data for the images; used for per pixel collision
  31. Color[] personTextureData;
  32. Color[] blockTextureData;
  33. // The images will be drawn with this SpriteBatch
  34. SpriteBatch spriteBatch;
  35. // Person
  36. Vector2 personPosition;
  37. const int PersonMoveSpeed = 5;
  38. // Blocks
  39. List<Vector2> blockPositions = new List<Vector2>();
  40. float BlockSpawnProbability = 0.01f;
  41. const int BlockFallSpeed = 2;
  42. Random random = new Random();
  43. // For when a collision is detected
  44. bool personHit = false;
  45. // The sub-rectangle of the drawable area which should be visible on all TVs
  46. Rectangle safeBounds;
  47. // Percentage of the screen on every side is the safe area
  48. const float SafeAreaPortion = 0.05f;
  49. public PerPixelCollisionGame()
  50. {
  51. graphics = new GraphicsDeviceManager(this);
  52. Content.RootDirectory = "Content";
  53. }
  54. /// <summary>
  55. /// Allows the game to perform any initialization it needs to before starting to
  56. /// run. This is where it can query for any required services and load any
  57. /// non-graphic related content. Calling base.Initialize will enumerate through
  58. /// any components and initialize them as well.
  59. /// </summary>
  60. protected override void Initialize()
  61. {
  62. base.Initialize();
  63. // Calculate safe bounds based on current resolution
  64. Viewport viewport = graphics.GraphicsDevice.Viewport;
  65. safeBounds = new Rectangle(
  66. (int)(viewport.Width * SafeAreaPortion),
  67. (int)(viewport.Height * SafeAreaPortion),
  68. (int)(viewport.Width * (1 - 2 * SafeAreaPortion)),
  69. (int)(viewport.Height * (1 - 2 * SafeAreaPortion)));
  70. // Start the player in the center along the bottom of the screen
  71. personPosition.X = (safeBounds.Width - personTexture.Width) / 2;
  72. personPosition.Y = safeBounds.Height - personTexture.Height;
  73. }
  74. /// <summary>
  75. /// Load your graphics content.
  76. /// </summary>
  77. protected override void LoadContent()
  78. {
  79. // Load textures
  80. blockTexture = Content.Load<Texture2D>("Block");
  81. personTexture = Content.Load<Texture2D>("Person");
  82. // Extract collision data
  83. blockTextureData =
  84. new Color[blockTexture.Width * blockTexture.Height];
  85. blockTexture.GetData(blockTextureData);
  86. personTextureData =
  87. new Color[personTexture.Width * personTexture.Height];
  88. personTexture.GetData(personTextureData);
  89. // Create a sprite batch to draw those textures
  90. spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
  91. }
  92. /// <summary>
  93. /// Allows the game to run logic such as updating the world,
  94. /// checking for collisions, gathering input and playing audio.
  95. /// </summary>
  96. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  97. protected override void Update(GameTime gameTime)
  98. {
  99. // Get input
  100. KeyboardState keyboard = Keyboard.GetState();
  101. GamePadState gamePad = GamePad.GetState(PlayerIndex.One);
  102. // Allows the game to exit
  103. if (gamePad.Buttons.Back == ButtonState.Pressed ||
  104. keyboard.IsKeyDown(Keys.Escape))
  105. {
  106. this.Exit();
  107. }
  108. // Move the player left and right with arrow keys or d-pad
  109. if (keyboard.IsKeyDown(Keys.Left) ||
  110. gamePad.DPad.Left == ButtonState.Pressed)
  111. {
  112. personPosition.X -= PersonMoveSpeed;
  113. }
  114. if (keyboard.IsKeyDown(Keys.Right) ||
  115. gamePad.DPad.Right == ButtonState.Pressed)
  116. {
  117. personPosition.X += PersonMoveSpeed;
  118. }
  119. // Prevent the person from moving off of the screen
  120. personPosition.X = MathHelper.Clamp(personPosition.X,
  121. safeBounds.Left, safeBounds.Right - personTexture.Width);
  122. // Spawn new falling blocks
  123. if (random.NextDouble() < BlockSpawnProbability)
  124. {
  125. float x = (float)random.NextDouble() *
  126. (Window.ClientBounds.Width - blockTexture.Width);
  127. blockPositions.Add(new Vector2(x, -blockTexture.Height));
  128. }
  129. // Get the bounding rectangle of the person
  130. Rectangle personRectangle =
  131. new Rectangle((int)personPosition.X, (int)personPosition.Y,
  132. personTexture.Width, personTexture.Height);
  133. // Update each block
  134. personHit = false;
  135. for (int i = 0; i < blockPositions.Count; i++)
  136. {
  137. // Animate this block falling
  138. blockPositions[i] =
  139. new Vector2(blockPositions[i].X,
  140. blockPositions[i].Y + BlockFallSpeed);
  141. // Get the bounding rectangle of this block
  142. Rectangle blockRectangle =
  143. new Rectangle((int)blockPositions[i].X, (int)blockPositions[i].Y,
  144. blockTexture.Width, blockTexture.Height);
  145. // Check collision with person
  146. if (IntersectPixels(personRectangle, personTextureData,
  147. blockRectangle, blockTextureData))
  148. {
  149. personHit = true;
  150. }
  151. // Remove this block if it have fallen off the screen
  152. if (blockPositions[i].Y > Window.ClientBounds.Height)
  153. {
  154. blockPositions.RemoveAt(i);
  155. // When removing a block, the next block will have the same index
  156. // as the current block. Decrement i to prevent skipping a block.
  157. i--;
  158. }
  159. }
  160. base.Update(gameTime);
  161. }
  162. /// <summary>
  163. /// This is called when the game should draw itself.
  164. /// </summary>
  165. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  166. protected override void Draw(GameTime gameTime)
  167. {
  168. GraphicsDevice device = graphics.GraphicsDevice;
  169. // Change the background to red when the person was hit by a block
  170. if (personHit)
  171. {
  172. device.Clear(Color.Red);
  173. }
  174. else
  175. {
  176. device.Clear(Color.CornflowerBlue);
  177. }
  178. spriteBatch.Begin();
  179. // Draw person
  180. spriteBatch.Draw(personTexture, personPosition, Color.White);
  181. // Draw blocks
  182. foreach (Vector2 blockPosition in blockPositions)
  183. spriteBatch.Draw(blockTexture, blockPosition, Color.White);
  184. spriteBatch.End();
  185. base.Draw(gameTime);
  186. }
  187. /// <summary>
  188. /// Determines if there is overlap of the non-transparent pixels
  189. /// between two sprites.
  190. /// </summary>
  191. /// <param name="rectangleA">Bounding rectangle of the first sprite</param>
  192. /// <param name="dataA">Pixel data of the first sprite</param>
  193. /// <param name="rectangleB">Bouding rectangle of the second sprite</param>
  194. /// <param name="dataB">Pixel data of the second sprite</param>
  195. /// <returns>True if non-transparent pixels overlap; false otherwise</returns>
  196. static bool IntersectPixels(Rectangle rectangleA, Color[] dataA,
  197. Rectangle rectangleB, Color[] dataB)
  198. {
  199. // Find the bounds of the rectangle intersection
  200. int top = Math.Max(rectangleA.Top, rectangleB.Top);
  201. int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
  202. int left = Math.Max(rectangleA.Left, rectangleB.Left);
  203. int right = Math.Min(rectangleA.Right, rectangleB.Right);
  204. // Check every point within the intersection bounds
  205. for (int y = top; y < bottom; y++)
  206. {
  207. for (int x = left; x < right; x++)
  208. {
  209. // Get the color of both pixels at this point
  210. Color colorA = dataA[(x - rectangleA.Left) +
  211. (y - rectangleA.Top) * rectangleA.Width];
  212. Color colorB = dataB[(x - rectangleB.Left) +
  213. (y - rectangleB.Top) * rectangleB.Width];
  214. // If both pixels are not completely transparent,
  215. if (colorA.A != 0 && colorB.A != 0)
  216. {
  217. // then an intersection has been found
  218. return true;
  219. }
  220. }
  221. }
  222. // No intersection found
  223. return false;
  224. }
  225. }
  226. }