TransformedCollisionGame.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. //-----------------------------------------------------------------------------
  2. // Game.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using System.Collections.Generic;
  9. using Microsoft.Xna.Framework;
  10. using Microsoft.Xna.Framework.Audio;
  11. using Microsoft.Xna.Framework.Content;
  12. using Microsoft.Xna.Framework.Graphics;
  13. using Microsoft.Xna.Framework.Input;
  14. namespace TransformedCollision
  15. {
  16. /// <summary>
  17. /// This is the main type for your game
  18. /// </summary>
  19. public class TransformedCollisionGame : Game
  20. {
  21. GraphicsDeviceManager graphics;
  22. // The images we will draw
  23. Texture2D personTexture;
  24. Texture2D blockTexture;
  25. // The color data for the images; used for per pixel collision
  26. Color[] personTextureData;
  27. Color[] blockTextureData;
  28. // The images will be drawn with this SpriteBatch
  29. SpriteBatch spriteBatch;
  30. // Person
  31. Vector2 personPosition;
  32. const int PersonMoveSpeed = 5;
  33. // Blocks
  34. List<Block> blocks = new List<Block>();
  35. float BlockSpawnProbability = 0.01f;
  36. const int BlockFallSpeed = 1;
  37. const float BlockRotateSpeed = 0.005f;
  38. Vector2 blockOrigin;
  39. Random random = new Random();
  40. // For when a collision is detected
  41. bool personHit = false;
  42. // The sub-rectangle of the drawable area which should be visible on all TVs
  43. Rectangle safeBounds;
  44. // Percentage of the screen on every side is the safe area
  45. const float SafeAreaPortion = 0.05f;
  46. public TransformedCollisionGame()
  47. {
  48. graphics = new GraphicsDeviceManager(this);
  49. Content.RootDirectory = "Content";
  50. }
  51. /// <summary>
  52. /// Allows the game to perform any initialization it needs to before starting to
  53. /// run. This is where it can query for any required services and load any
  54. /// non-graphic related content. Calling base.Initialize will enumerate through
  55. /// any components and initialize them as well.
  56. /// </summary>
  57. protected override void Initialize()
  58. {
  59. base.Initialize();
  60. // Calculate safe bounds based on current resolution
  61. Viewport viewport = graphics.GraphicsDevice.Viewport;
  62. safeBounds = new Rectangle(
  63. (int)(viewport.Width * SafeAreaPortion),
  64. (int)(viewport.Height * SafeAreaPortion),
  65. (int)(viewport.Width * (1 - 2 * SafeAreaPortion)),
  66. (int)(viewport.Height * (1 - 2 * SafeAreaPortion)));
  67. // Start the player in the center along the bottom of the screen
  68. personPosition.X = (safeBounds.Width - personTexture.Width) / 2;
  69. personPosition.Y = safeBounds.Height - personTexture.Height;
  70. }
  71. /// <summary>
  72. /// Load your graphics content.
  73. /// </summary>
  74. protected override void LoadContent()
  75. {
  76. // Load textures
  77. blockTexture = Content.Load<Texture2D>("SpinnerBlock");
  78. personTexture = Content.Load<Texture2D>("Person");
  79. // Extract collision data
  80. blockTextureData =
  81. new Color[blockTexture.Width * blockTexture.Height];
  82. blockTexture.GetData(blockTextureData);
  83. personTextureData =
  84. new Color[personTexture.Width * personTexture.Height];
  85. personTexture.GetData(personTextureData);
  86. // Calculate the block origin
  87. blockOrigin =
  88. new Vector2(blockTexture.Width / 2, blockTexture.Height / 2);
  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. // Update the person's transform
  123. Matrix personTransform =
  124. Matrix.CreateTranslation(new Vector3(personPosition, 0.0f));
  125. // Spawn new falling blocks
  126. if (random.NextDouble() < BlockSpawnProbability)
  127. {
  128. Block newBlock = new Block();
  129. // at a random position just above the screen
  130. float x = (float)random.NextDouble() *
  131. (Window.ClientBounds.Width - blockTexture.Width);
  132. newBlock.Position = new Vector2(x, -blockTexture.Height);
  133. // with a random rotation
  134. newBlock.Rotation = (float)random.NextDouble() * MathHelper.TwoPi;
  135. blocks.Add(newBlock);
  136. }
  137. // Get the bounding rectangle of the person
  138. Rectangle personRectangle =
  139. new Rectangle((int)personPosition.X, (int)personPosition.Y,
  140. personTexture.Width, personTexture.Height);
  141. // Update each block
  142. personHit = false;
  143. for (int i = 0; i < blocks.Count; i++)
  144. {
  145. // Animate this block falling
  146. blocks[i].Position += new Vector2(0.0f, BlockFallSpeed);
  147. blocks[i].Rotation += BlockRotateSpeed;
  148. // Build the block's transform
  149. Matrix blockTransform =
  150. Matrix.CreateTranslation(new Vector3(-blockOrigin, 0.0f)) *
  151. // Matrix.CreateScale(block.Scale) * would go here
  152. Matrix.CreateRotationZ(blocks[i].Rotation) *
  153. Matrix.CreateTranslation(new Vector3(blocks[i].Position, 0.0f));
  154. // Calculate the bounding rectangle of this block in world space
  155. Rectangle blockRectangle = CalculateBoundingRectangle(
  156. new Rectangle(0, 0, blockTexture.Width, blockTexture.Height),
  157. blockTransform);
  158. // The per-pixel check is expensive, so check the bounding rectangles
  159. // first to prevent testing pixels when collisions are impossible.
  160. if (personRectangle.Intersects(blockRectangle))
  161. {
  162. // Check collision with person
  163. if (IntersectPixels(personTransform, personTexture.Width,
  164. personTexture.Height, personTextureData,
  165. blockTransform, blockTexture.Width,
  166. blockTexture.Height, blockTextureData))
  167. {
  168. personHit = true;
  169. }
  170. }
  171. // Remove this block if it have fallen off the screen
  172. if (blocks[i].Position.Y >
  173. Window.ClientBounds.Height + blockOrigin.Length())
  174. {
  175. blocks.RemoveAt(i);
  176. // When removing a block, the next block will have the same index
  177. // as the current block. Decrement i to prevent skipping a block.
  178. i--;
  179. }
  180. }
  181. base.Update(gameTime);
  182. }
  183. /// <summary>
  184. /// This is called when the game should draw itself.
  185. /// </summary>
  186. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  187. protected override void Draw(GameTime gameTime)
  188. {
  189. GraphicsDevice device = graphics.GraphicsDevice;
  190. // Change the background to red when the person was hit by a block
  191. if (personHit)
  192. {
  193. device.Clear(Color.Yellow);
  194. }
  195. else
  196. {
  197. device.Clear(Color.MonoGameOrange);
  198. }
  199. spriteBatch.Begin();
  200. // Draw person
  201. spriteBatch.Draw(personTexture, personPosition, Color.White);
  202. // Draw blocks
  203. foreach (Block block in blocks)
  204. {
  205. spriteBatch.Draw(blockTexture, block.Position, null, Color.White,
  206. block.Rotation, blockOrigin, 1.0f, SpriteEffects.None, 0.0f);
  207. }
  208. spriteBatch.End();
  209. base.Draw(gameTime);
  210. }
  211. /// <summary>
  212. /// Determines if there is overlap of the non-transparent pixels
  213. /// between two sprites.
  214. /// </summary>
  215. /// <param name="rectangleA">Bounding rectangle of the first sprite</param>
  216. /// <param name="dataA">Pixel data of the first sprite</param>
  217. /// <param name="rectangleB">Bouding rectangle of the second sprite</param>
  218. /// <param name="dataB">Pixel data of the second sprite</param>
  219. /// <returns>True if non-transparent pixels overlap; false otherwise</returns>
  220. public static bool IntersectPixels(Rectangle rectangleA, Color[] dataA,
  221. Rectangle rectangleB, Color[] dataB)
  222. {
  223. // Find the bounds of the rectangle intersection
  224. int top = Math.Max(rectangleA.Top, rectangleB.Top);
  225. int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
  226. int left = Math.Max(rectangleA.Left, rectangleB.Left);
  227. int right = Math.Min(rectangleA.Right, rectangleB.Right);
  228. // Check every point within the intersection bounds
  229. for (int y = top; y < bottom; y++)
  230. {
  231. for (int x = left; x < right; x++)
  232. {
  233. // Get the color of both pixels at this point
  234. Color colorA = dataA[(x - rectangleA.Left) +
  235. (y - rectangleA.Top) * rectangleA.Width];
  236. Color colorB = dataB[(x - rectangleB.Left) +
  237. (y - rectangleB.Top) * rectangleB.Width];
  238. // If both pixels are not completely transparent,
  239. if (colorA.A != 0 && colorB.A != 0)
  240. {
  241. // then an intersection has been found
  242. return true;
  243. }
  244. }
  245. }
  246. // No intersection found
  247. return false;
  248. }
  249. /// <summary>
  250. /// Determines if there is overlap of the non-transparent pixels between two
  251. /// sprites.
  252. /// </summary>
  253. /// <param name="transformA">World transform of the first sprite.</param>
  254. /// <param name="widthA">Width of the first sprite's texture.</param>
  255. /// <param name="heightA">Height of the first sprite's texture.</param>
  256. /// <param name="dataA">Pixel color data of the first sprite.</param>
  257. /// <param name="transformB">World transform of the second sprite.</param>
  258. /// <param name="widthB">Width of the second sprite's texture.</param>
  259. /// <param name="heightB">Height of the second sprite's texture.</param>
  260. /// <param name="dataB">Pixel color data of the second sprite.</param>
  261. /// <returns>True if non-transparent pixels overlap; false otherwise</returns>
  262. public static bool IntersectPixels(
  263. Matrix transformA, int widthA, int heightA, Color[] dataA,
  264. Matrix transformB, int widthB, int heightB, Color[] dataB)
  265. {
  266. // Calculate a matrix which transforms from A's local space into
  267. // world space and then into B's local space
  268. Matrix transformAToB = transformA * Matrix.Invert(transformB);
  269. // When a point moves in A's local space, it moves in B's local space with a
  270. // fixed direction and distance proportional to the movement in A.
  271. // This algorithm steps through A one pixel at a time along A's X and Y axes
  272. // Calculate the analogous steps in B:
  273. Vector2 stepX = Vector2.TransformNormal(Vector2.UnitX, transformAToB);
  274. Vector2 stepY = Vector2.TransformNormal(Vector2.UnitY, transformAToB);
  275. // Calculate the top left corner of A in B's local space
  276. // This variable will be reused to keep track of the start of each row
  277. Vector2 yPosInB = Vector2.Transform(Vector2.Zero, transformAToB);
  278. // For each row of pixels in A
  279. for (int yA = 0; yA < heightA; yA++)
  280. {
  281. // Start at the beginning of the row
  282. Vector2 posInB = yPosInB;
  283. // For each pixel in this row
  284. for (int xA = 0; xA < widthA; xA++)
  285. {
  286. // Round to the nearest pixel
  287. int xB = (int)Math.Round(posInB.X);
  288. int yB = (int)Math.Round(posInB.Y);
  289. // If the pixel lies within the bounds of B
  290. if (0 <= xB && xB < widthB &&
  291. 0 <= yB && yB < heightB)
  292. {
  293. // Get the colors of the overlapping pixels
  294. Color colorA = dataA[xA + yA * widthA];
  295. Color colorB = dataB[xB + yB * widthB];
  296. // If both pixels are not completely transparent,
  297. if (colorA.A != 0 && colorB.A != 0)
  298. {
  299. // then an intersection has been found
  300. return true;
  301. }
  302. }
  303. // Move to the next pixel in the row
  304. posInB += stepX;
  305. }
  306. // Move to the next row
  307. yPosInB += stepY;
  308. }
  309. // No intersection found
  310. return false;
  311. }
  312. /// <summary>
  313. /// Calculates an axis aligned rectangle which fully contains an arbitrarily
  314. /// transformed axis aligned rectangle.
  315. /// </summary>
  316. /// <param name="rectangle">Original bounding rectangle.</param>
  317. /// <param name="transform">World transform of the rectangle.</param>
  318. /// <returns>A new rectangle which contains the trasnformed rectangle.</returns>
  319. public static Rectangle CalculateBoundingRectangle(Rectangle rectangle,
  320. Matrix transform)
  321. {
  322. // Get all four corners in local space
  323. Vector2 leftTop = new Vector2(rectangle.Left, rectangle.Top);
  324. Vector2 rightTop = new Vector2(rectangle.Right, rectangle.Top);
  325. Vector2 leftBottom = new Vector2(rectangle.Left, rectangle.Bottom);
  326. Vector2 rightBottom = new Vector2(rectangle.Right, rectangle.Bottom);
  327. // Transform all four corners into work space
  328. Vector2.Transform(ref leftTop, ref transform, out leftTop);
  329. Vector2.Transform(ref rightTop, ref transform, out rightTop);
  330. Vector2.Transform(ref leftBottom, ref transform, out leftBottom);
  331. Vector2.Transform(ref rightBottom, ref transform, out rightBottom);
  332. // Find the minimum and maximum extents of the rectangle in world space
  333. Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop),
  334. Vector2.Min(leftBottom, rightBottom));
  335. Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop),
  336. Vector2.Max(leftBottom, rightBottom));
  337. // Return that as a rectangle
  338. return new Rectangle((int)min.X, (int)min.Y,
  339. (int)(max.X - min.X), (int)(max.Y - min.Y));
  340. }
  341. }
  342. }