Game1.cs 11 KB

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