ChaseAndEvadeGame.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. #if ANDROID
  12. using Android.App;
  13. #endif
  14. using Microsoft.Xna.Framework;
  15. using Microsoft.Xna.Framework.Audio;
  16. using Microsoft.Xna.Framework.Graphics;
  17. using Microsoft.Xna.Framework.Input;
  18. using Microsoft.Xna.Framework.Input.Touch;
  19. using Microsoft.Xna.Framework.Storage;
  20. using Microsoft.Xna.Framework.Content;
  21. using Microsoft.Xna.Framework.Media;
  22. #endregion
  23. namespace ChaseAndEvade
  24. {
  25. /// <summary>
  26. /// Sample showing how to implement simple chase, evade, and wander AI behaviors.
  27. /// The behaviors are based on the TurnToFace function, which was explained in
  28. /// AI Sample 1: Aiming.
  29. /// </summary>
  30. public class ChaseAndEvadeGame : Game
  31. {
  32. /// <summary>
  33. /// TankAiState is used to keep track of what the tank is currently doing.
  34. /// </summary>
  35. enum TankAiState
  36. {
  37. // chasing the cat
  38. Chasing,
  39. // the tank has gotten close enough that the cat that it can stop chasing it
  40. Caught,
  41. // the tank can't "see" the cat, and is wandering around.
  42. Wander
  43. }
  44. /// <summary>
  45. /// MouseAiState is used to keep track of what the mouse is currently doing.
  46. /// </summary>
  47. enum MouseAiState
  48. {
  49. // evading the cat
  50. Evading,
  51. // the mouse can't see the "cat", and it's wandering around.
  52. Wander
  53. }
  54. #region Constants
  55. // The following values control the different characteristics of the characters
  56. // in this sample, including their speed, turning rates. distances are specified
  57. // in pixels, angles are specified in radians.
  58. // how fast can the cat move?
  59. const float MaxCatSpeed = 7.5f;
  60. // how fast can the tank move?
  61. const float MaxTankSpeed = 5.0f;
  62. // how fast can he turn?
  63. const float TankTurnSpeed = 0.10f;
  64. // this value controls the distance at which the tank will start to chase the
  65. // cat.
  66. const float TankChaseDistance = 250.0f;
  67. // TankCaughtDistance controls the distance at which the tank will stop because
  68. // he has "caught" the cat.
  69. const float TankCaughtDistance = 60.0f;
  70. // this constant is used to avoid hysteresis, which is common in ai programming.
  71. // see the doc for more details.
  72. const float TankHysteresis = 15.0f;
  73. // how fast can the mouse move?
  74. const float MaxMouseSpeed = 8.5f;
  75. // and how fast can it turn?
  76. const float MouseTurnSpeed = 0.20f;
  77. // MouseEvadeDistance controls the distance at which the mouse will flee from
  78. // cat. If the mouse is further than "MouseEvadeDistance" pixels away, he will
  79. // consider himself safe.
  80. const float MouseEvadeDistance = 200.0f;
  81. // this constant is similar to TankHysteresis. The value is larger than the
  82. // tank's hysteresis value because the mouse is faster than the tank: with a
  83. // higher velocity, small fluctuations are much more visible.
  84. const float MouseHysteresis = 60.0f;
  85. #endregion
  86. #region Fields
  87. GraphicsDeviceManager graphics;
  88. SpriteBatch spriteBatch;
  89. SpriteFont spriteFont;
  90. Texture2D tankTexture;
  91. Vector2 tankTextureCenter;
  92. Vector2 tankPosition;
  93. TankAiState tankState = TankAiState.Wander;
  94. float tankOrientation;
  95. Vector2 tankWanderDirection;
  96. Texture2D catTexture;
  97. Vector2 catTextureCenter;
  98. Vector2 catPosition;
  99. Texture2D mouseTexture;
  100. Vector2 mouseTextureCenter;
  101. Vector2 mousePosition;
  102. MouseAiState mouseState = MouseAiState.Wander;
  103. float mouseOrientation;
  104. Vector2 mouseWanderDirection;
  105. Random random = new Random ();
  106. #endregion
  107. #region Initialization
  108. public ChaseAndEvadeGame ()
  109. {
  110. graphics = new GraphicsDeviceManager (this);
  111. Content.RootDirectory = "Content";
  112. #if WINDOWS_PHONE
  113. graphics.SupportedOrientations = DisplayOrientation.Portrait;
  114. graphics.PreferredBackBufferWidth = 480;
  115. graphics.PreferredBackBufferHeight = 800;
  116. TargetElapsedTime = TimeSpan.FromTicks(333333);
  117. #elif !MONOMAC
  118. graphics.PreferredBackBufferWidth = 320;
  119. graphics.PreferredBackBufferHeight = 480;
  120. #endif
  121. graphics.IsFullScreen = true;
  122. }
  123. /// <summary>
  124. /// Overridden from the base Game.Initialize. Once the GraphicsDevice is setup,
  125. /// we'll use the viewport to initialize some values.
  126. /// </summary>
  127. protected override void Initialize ()
  128. {
  129. base.Initialize ();
  130. // once base.Initialize has finished, the GraphicsDevice will have been
  131. // created, and we'll know how big the Viewport is. We want the tank, cat
  132. // and mouse to be spread out across the screen, so we'll use the viewport
  133. // to figure out where they should be.
  134. Viewport vp = graphics.GraphicsDevice.Viewport;
  135. tankPosition = new Vector2 (vp.Width / 4, vp.Height / 2);
  136. catPosition = new Vector2 (vp.Width / 2, vp.Height / 2);
  137. mousePosition = new Vector2 (3 * vp.Width / 4, vp.Height / 2);
  138. }
  139. /// <summary>
  140. /// Load your graphics content.
  141. /// </summary>
  142. protected override void LoadContent ()
  143. {
  144. // create a SpriteBatch, and load the textures and font that we'll need
  145. // during the game.
  146. spriteBatch = new SpriteBatch (graphics.GraphicsDevice);
  147. spriteFont = Content.Load<SpriteFont> ("Arial");
  148. tankTexture = Content.Load<Texture2D> ("tank");
  149. catTexture = Content.Load<Texture2D> ("cat");
  150. mouseTexture = Content.Load<Texture2D> ("mouse");
  151. // once all the content is loaded, we can calculate the centers of each
  152. // of the textures that we loaded. Just like in the previous sample in
  153. // this series, the aiming sample, we want spriteBatch to draw the
  154. // textures centered on their position vectors. SpriteBatch.Draw will
  155. // center the sprite on the vector that we pass in as the "origin"
  156. // parameter, so we'll just calculate that to be the middle of
  157. // the texture.
  158. tankTextureCenter =
  159. new Vector2 (tankTexture.Width / 2, tankTexture.Height / 2);
  160. catTextureCenter =
  161. new Vector2 (catTexture.Width / 2, catTexture.Height / 2);
  162. mouseTextureCenter =
  163. new Vector2 (mouseTexture.Width / 2, mouseTexture.Height / 2);
  164. }
  165. #endregion
  166. #region Update and Draw
  167. /// <summary>
  168. /// Allows the game to run logic.
  169. /// </summary>
  170. protected override void Update (GameTime gameTime)
  171. {
  172. // handle input will read the controller input, and update the cat
  173. // to move according to the user's whim.
  174. HandleInput ();
  175. // UpdateTank will run the AI code that controls the tank's movement...
  176. UpdateTank ();
  177. // ... and UpdateMouse does the same thing for the mouse.
  178. UpdateMouse ();
  179. // Once we've finished that, we'll use the ClampToViewport helper function
  180. // to clamp everyone's position so that they stay on the screen.
  181. tankPosition = ClampToViewport (tankPosition);
  182. catPosition = ClampToViewport (catPosition);
  183. mousePosition = ClampToViewport (mousePosition);
  184. base.Update (gameTime);
  185. }
  186. /// <summary>
  187. /// This function takes a Vector2 as input, and returns that vector "clamped"
  188. /// to the current graphics viewport. We use this function to make sure that
  189. /// no one can go off of the screen.
  190. /// </summary>
  191. /// <param name="vector">an input vector</param>
  192. /// <returns>the input vector, clamped between the minimum and maximum of the
  193. /// viewport.</returns>
  194. private Vector2 ClampToViewport (Vector2 vector)
  195. {
  196. Viewport vp = graphics.GraphicsDevice.Viewport;
  197. vector.X = MathHelper.Clamp (vector.X, vp.X, vp.X + vp.Width);
  198. vector.Y = MathHelper.Clamp (vector.Y, vp.Y, vp.Y + vp.Height);
  199. return vector;
  200. }
  201. /// <summary>
  202. /// This function contains the code that controls the mouse. It decides what the
  203. /// mouse should do based on the position of the cat: if the cat is too close,
  204. /// it will attempt to flee. Otherwise, it will idly wander around the screen.
  205. ///
  206. /// </summary>
  207. private void UpdateMouse ()
  208. {
  209. // first, calculate how far away the mouse is from the cat, and use that
  210. // information to decide how to behave. If they are too close, the mouse
  211. // will switch to "active" mode - fleeing. if they are far apart, the mouse
  212. // will switch to "idle" mode, where it roams around the screen.
  213. // we use a hysteresis constant in the decision making process, as described
  214. // in the accompanying doc file.
  215. float distanceFromCat = Vector2.Distance (mousePosition, catPosition);
  216. // the cat is a safe distance away, so the mouse should idle:
  217. if (distanceFromCat > MouseEvadeDistance + MouseHysteresis) {
  218. mouseState = MouseAiState.Wander;
  219. }
  220. // the cat is too close; the mouse should run:
  221. else if (distanceFromCat < MouseEvadeDistance - MouseHysteresis) {
  222. mouseState = MouseAiState.Evading;
  223. }
  224. // if neither of those if blocks hit, we are in the "hysteresis" range,
  225. // and the mouse will continue doing whatever it is doing now.
  226. // the mouse will move at a different speed depending on what state it
  227. // is in. when idle it won't move at full speed, but when actively evading
  228. // it will move as fast as it can. this variable is used to track which
  229. // speed the mouse should be moving.
  230. float currentMouseSpeed;
  231. // the second step of the Update is to change the mouse's orientation based
  232. // on its current state.
  233. if (mouseState == MouseAiState.Evading) {
  234. // If the mouse is "active," it is trying to evade the cat. The evasion
  235. // behavior is accomplished by using the TurnToFace function to turn
  236. // towards a point on a straight line facing away from the cat. In other
  237. // words, if the cat is point A, and the mouse is point B, the "seek
  238. // point" is C.
  239. // C
  240. // B
  241. // A
  242. Vector2 seekPosition = 2 * mousePosition - catPosition;
  243. // Use the TurnToFace function, which we introduced in the AI Series 1:
  244. // Aiming sample, to turn the mouse towards the seekPosition. Now when
  245. // the mouse moves forward, it'll be trying to move in a straight line
  246. // away from the cat.
  247. mouseOrientation = TurnToFace (mousePosition, seekPosition,
  248. mouseOrientation, MouseTurnSpeed);
  249. // set currentMouseSpeed to MaxMouseSpeed - the mouse should run as fast
  250. // as it can.
  251. currentMouseSpeed = MaxMouseSpeed;
  252. } else {
  253. // if the mouse isn't trying to evade the cat, it should just meander
  254. // around the screen. we'll use the Wander function, which the mouse and
  255. // tank share, to accomplish this. mouseWanderDirection and
  256. // mouseOrientation are passed by ref so that the wander function can
  257. // modify them. for more information on ref parameters, see
  258. // http://msdn2.microsoft.com/en-us/library/14akc2c7(VS.80).aspx
  259. Wander (mousePosition, ref mouseWanderDirection, ref mouseOrientation,
  260. MouseTurnSpeed);
  261. // if the mouse is wandering, it should only move at 25% of its maximum
  262. // speed.
  263. currentMouseSpeed = .25f * MaxMouseSpeed;
  264. }
  265. // The final step is to move the mouse forward based on its current
  266. // orientation. First, we construct a "heading" vector from the orientation
  267. // angle. To do this, we'll use Cosine and Sine to tell us the x and y
  268. // components of the heading vector. See the accompanying doc for more
  269. // information.
  270. Vector2 heading = new Vector2 (
  271. (float)Math.Cos (mouseOrientation), (float)Math.Sin (mouseOrientation));
  272. // by multiplying the heading and speed, we can get a velocity vector. the
  273. // velocity vector is then added to the mouse's current position, moving him
  274. // forward.
  275. mousePosition += heading * currentMouseSpeed;
  276. }
  277. /// <summary>
  278. /// UpdateTank runs the AI code that will update the tank's orientation and
  279. /// position. It is very similar to UpdateMouse, but is slightly more
  280. /// complicated: where mouse only has two states, idle and active, the Tank has
  281. /// three.
  282. /// </summary>
  283. private void UpdateTank ()
  284. {
  285. // However, the tank's behavior is more complicated than the mouse's, and so
  286. // the decision making process is a little different.
  287. // First we have to use the current state to decide what the thresholds are
  288. // for changing state, as described in the doc.
  289. float tankChaseThreshold = TankChaseDistance;
  290. float tankCaughtThreshold = TankCaughtDistance;
  291. // if the tank is idle, he prefers to stay idle. we do this by making the
  292. // chase distance smaller, so the tank will be less likely to begin chasing
  293. // the cat.
  294. if (tankState == TankAiState.Wander) {
  295. tankChaseThreshold -= TankHysteresis / 2;
  296. }
  297. // similarly, if the tank is active, he prefers to stay active. we
  298. // accomplish this by increasing the range of values that will cause the
  299. // tank to go into the active state.
  300. else if (tankState == TankAiState.Chasing) {
  301. tankChaseThreshold += TankHysteresis / 2;
  302. tankCaughtThreshold -= TankHysteresis / 2;
  303. }
  304. // the same logic is applied to the finished state.
  305. else if (tankState == TankAiState.Caught) {
  306. tankCaughtThreshold += TankHysteresis / 2;
  307. }
  308. // Second, now that we know what the thresholds are, we compare the tank's
  309. // distance from the cat against the thresholds to decide what the tank's
  310. // current state is.
  311. float distanceFromCat = Vector2.Distance (tankPosition, catPosition);
  312. if (distanceFromCat > tankChaseThreshold) {
  313. // just like the mouse, if the tank is far away from the cat, it should
  314. // idle.
  315. tankState = TankAiState.Wander;
  316. } else if (distanceFromCat > tankCaughtThreshold) {
  317. tankState = TankAiState.Chasing;
  318. } else {
  319. tankState = TankAiState.Caught;
  320. }
  321. // Third, once we know what state we're in, act on that state.
  322. float currentTankSpeed;
  323. if (tankState == TankAiState.Chasing) {
  324. // the tank wants to chase the cat, so it will just use the TurnToFace
  325. // function to turn towards the cat's position. Then, when the tank
  326. // moves forward, he will chase the cat.
  327. tankOrientation = TurnToFace (tankPosition, catPosition, tankOrientation,
  328. TankTurnSpeed);
  329. currentTankSpeed = MaxTankSpeed;
  330. } else if (tankState == TankAiState.Wander) {
  331. // wander works just like the mouse's.
  332. Wander (tankPosition, ref tankWanderDirection, ref tankOrientation,
  333. TankTurnSpeed);
  334. currentTankSpeed = .25f * MaxTankSpeed;
  335. } else {
  336. // this part is different from the mouse. if the tank catches the cat,
  337. // it should stop. otherwise it will run right by, then spin around and
  338. // try to catch it all over again. The end result is that it will kind
  339. // of "run laps" around the cat, which looks funny, but is not what
  340. // we're after.
  341. currentTankSpeed = 0.0f;
  342. }
  343. // this calculation is also just like the mouse's: we construct a heading
  344. // vector based on the tank's orientation, and then make the tank move along
  345. // that heading.
  346. Vector2 heading = new Vector2 (
  347. (float)Math.Cos (tankOrientation), (float)Math.Sin (tankOrientation));
  348. tankPosition += heading * currentTankSpeed;
  349. }
  350. /// <summary>
  351. /// Wander contains functionality that is shared between both the mouse and the
  352. /// tank, and does just what its name implies: makes them wander around the
  353. /// screen. The specifics of the function are described in more detail in the
  354. /// accompanying doc.
  355. /// </summary>
  356. /// <param name="position">the position of the character that is wandering
  357. /// </param>
  358. /// <param name="wanderDirection">the direction that the character is currently
  359. /// wandering. this parameter is passed by reference because it is an input and
  360. /// output parameter: Wander accepts it as input, and will update it as well.
  361. /// </param>
  362. /// <param name="orientation">the character's orientation. this parameter is
  363. /// also passed by reference and is an input/output parameter.</param>
  364. /// <param name="turnSpeed">the character's maximum turning speed.</param>
  365. private void Wander (Vector2 position, ref Vector2 wanderDirection,
  366. ref float orientation, float turnSpeed)
  367. {
  368. // The wander effect is accomplished by having the character aim in a random
  369. // direction. Every frame, this random direction is slightly modified.
  370. // Finally, to keep the characters on the center of the screen, we have them
  371. // turn to face the screen center. The further they are from the screen
  372. // center, the more they will aim back towards it.
  373. // the first step of the wander behavior is to use the random number
  374. // generator to offset the current wanderDirection by some random amount.
  375. // .25 is a bit of a magic number, but it controls how erratic the wander
  376. // behavior is. Larger numbers will make the characters "wobble" more,
  377. // smaller numbers will make them more stable. we want just enough
  378. // wobbliness to be interesting without looking odd.
  379. wanderDirection.X +=
  380. MathHelper.Lerp (-.25f, .25f, (float)random.NextDouble ());
  381. wanderDirection.Y +=
  382. MathHelper.Lerp (-.25f, .25f, (float)random.NextDouble ());
  383. // we'll renormalize the wander direction, ...
  384. if (wanderDirection != Vector2.Zero) {
  385. wanderDirection.Normalize ();
  386. }
  387. // ... and then turn to face in the wander direction. We don't turn at the
  388. // maximum turning speed, but at 15% of it. Again, this is a bit of a magic
  389. // number: it works well for this sample, but feel free to tweak it.
  390. orientation = TurnToFace (position, position + wanderDirection, orientation,
  391. .15f * turnSpeed);
  392. // next, we'll turn the characters back towards the center of the screen, to
  393. // prevent them from getting stuck on the edges of the screen.
  394. Vector2 screenCenter = Vector2.Zero;
  395. screenCenter.X = graphics.GraphicsDevice.Viewport.Width / 2;
  396. screenCenter.Y = graphics.GraphicsDevice.Viewport.Height / 2;
  397. // Here we are creating a curve that we can apply to the turnSpeed. This
  398. // curve will make it so that if we are close to the center of the screen,
  399. // we won't turn very much. However, the further we are from the screen
  400. // center, the more we turn. At most, we will turn at 30% of our maximum
  401. // turn speed. This too is a "magic number" which works well for the sample.
  402. // Feel free to play around with this one as well: smaller values will make
  403. // the characters explore further away from the center, but they may get
  404. // stuck on the walls. Larger numbers will hold the characters to center of
  405. // the screen. If the number is too large, the characters may end up
  406. // "orbiting" the center.
  407. float distanceFromScreenCenter = Vector2.Distance (screenCenter, position);
  408. float MaxDistanceFromScreenCenter =
  409. Math.Min (screenCenter.Y, screenCenter.X);
  410. float normalizedDistance =
  411. distanceFromScreenCenter / MaxDistanceFromScreenCenter;
  412. float turnToCenterSpeed = .3f * normalizedDistance * normalizedDistance *
  413. turnSpeed;
  414. // once we've calculated how much we want to turn towards the center, we can
  415. // use the TurnToFace function to actually do the work.
  416. orientation = TurnToFace (position, screenCenter, orientation,
  417. turnToCenterSpeed);
  418. }
  419. /// <summary>
  420. /// Calculates the angle that an object should face, given its position, its
  421. /// target's position, its current angle, and its maximum turning speed.
  422. /// </summary>
  423. private static float TurnToFace (Vector2 position, Vector2 faceThis,
  424. float currentAngle, float turnSpeed)
  425. {
  426. // consider this diagram:
  427. // B
  428. // /|
  429. // / |
  430. // / | y
  431. // / o |
  432. // A--------
  433. // x
  434. //
  435. // where A is the position of the object, B is the position of the target,
  436. // and "o" is the angle that the object should be facing in order to
  437. // point at the target. we need to know what o is. using trig, we know that
  438. // tan(theta) = opposite / adjacent
  439. // tan(o) = y / x
  440. // if we take the arctan of both sides of this equation...
  441. // arctan( tan(o) ) = arctan( y / x )
  442. // o = arctan( y / x )
  443. // so, we can use x and y to find o, our "desiredAngle."
  444. // x and y are just the differences in position between the two objects.
  445. float x = faceThis.X - position.X;
  446. float y = faceThis.Y - position.Y;
  447. // we'll use the Atan2 function. Atan will calculates the arc tangent of
  448. // y / x for us, and has the added benefit that it will use the signs of x
  449. // and y to determine what cartesian quadrant to put the result in.
  450. // http://msdn2.microsoft.com/en-us/library/system.math.atan2.aspx
  451. float desiredAngle = (float)Math.Atan2 (y, x);
  452. // so now we know where we WANT to be facing, and where we ARE facing...
  453. // if we weren't constrained by turnSpeed, this would be easy: we'd just
  454. // return desiredAngle.
  455. // instead, we have to calculate how much we WANT to turn, and then make
  456. // sure that's not more than turnSpeed.
  457. // first, figure out how much we want to turn, using WrapAngle to get our
  458. // result from -Pi to Pi ( -180 degrees to 180 degrees )
  459. float difference = WrapAngle (desiredAngle - currentAngle);
  460. // clamp that between -turnSpeed and turnSpeed.
  461. difference = MathHelper.Clamp (difference, -turnSpeed, turnSpeed);
  462. // so, the closest we can get to our target is currentAngle + difference.
  463. // return that, using WrapAngle again.
  464. return WrapAngle (currentAngle + difference);
  465. }
  466. /// <summary>
  467. /// Returns the angle expressed in radians between -Pi and Pi.
  468. /// <param name="radians">the angle to wrap, in radians.</param>
  469. /// <returns>the input value expressed in radians from -Pi to Pi.</returns>
  470. /// </summary>
  471. private static float WrapAngle (float radians)
  472. {
  473. while (radians < -MathHelper.Pi) {
  474. radians += MathHelper.TwoPi;
  475. }
  476. while (radians > MathHelper.Pi) {
  477. radians -= MathHelper.TwoPi;
  478. }
  479. return radians;
  480. }
  481. /// <summary>
  482. /// This is called when the game should draw itself. Nothing too fancy in here,
  483. /// we'll just call Begin on the SpriteBatch, and then draw the tank, cat, and
  484. /// mouse, and some overlay text. Once we're finished drawing, we'll call
  485. /// SpriteBatch.End.
  486. /// </summary>
  487. protected override void Draw (GameTime gameTime)
  488. {
  489. GraphicsDevice device = graphics.GraphicsDevice;
  490. device.Clear (Color.CornflowerBlue);
  491. spriteBatch.Begin ();
  492. // draw the tank, cat and mouse...
  493. spriteBatch.Draw (tankTexture, tankPosition, null, Color.White,
  494. tankOrientation, tankTextureCenter, 1.0f, SpriteEffects.None, 0.0f);
  495. spriteBatch.Draw (catTexture, catPosition, null, Color.White,
  496. 0.0f, catTextureCenter, 1.0f, SpriteEffects.None, 0.0f);
  497. spriteBatch.Draw (mouseTexture, mousePosition, null, Color.White,
  498. mouseOrientation, mouseTextureCenter, 1.0f, SpriteEffects.None, 0.0f);
  499. // and then draw some text showing the tank's and mouse's current state.
  500. // to make the text stand out more, we'll draw the text twice, once black
  501. // and once white, to create a drop shadow effect.
  502. Vector2 shadowOffset = Vector2.One;
  503. spriteBatch.DrawString (spriteFont, "Tank State: \n" + tankState.ToString (),
  504. new Vector2 (10, 10) + shadowOffset, Color.Black);
  505. spriteBatch.DrawString (spriteFont, "Tank State: \n" + tankState.ToString (),
  506. new Vector2 (10, 10), Color.White);
  507. spriteBatch.DrawString (spriteFont, "Mouse State: \n" + mouseState.ToString (),
  508. new Vector2 (10, 90) + shadowOffset, Color.Black);
  509. spriteBatch.DrawString (spriteFont, "Mouse State: \n" + mouseState.ToString (),
  510. new Vector2 (10, 90), Color.White);
  511. spriteBatch.End ();
  512. base.Draw (gameTime);
  513. }
  514. #endregion
  515. #region Handle Input
  516. /// <summary>
  517. /// Handles input for quitting the game.
  518. /// </summary>
  519. void HandleInput ()
  520. {
  521. #if WINDOWS_PHONE
  522. KeyboardState currentKeyboardState = new KeyboardState();
  523. #else
  524. KeyboardState currentKeyboardState = Keyboard.GetState ();
  525. MouseState currentMouseState = Mouse.GetState ();
  526. #endif
  527. #if IPHONE
  528. GamePadState currentGamePadState = GamePad.GetState (PlayerIndex.One);
  529. // Check for exit.
  530. if (currentKeyboardState.IsKeyDown (Keys.Escape) ||
  531. currentGamePadState.Buttons.Back == ButtonState.Pressed) {
  532. Exit ();
  533. }
  534. #else
  535. // Check for exit.
  536. if (currentKeyboardState.IsKeyDown (Keys.Escape)) {
  537. Exit ();
  538. }
  539. #endif
  540. // check to see if the user wants to move the cat. we'll create a vector
  541. // called catMovement, which will store the sum of all the user's inputs.
  542. Vector2 catMovement = Vector2.Zero;
  543. //Move toward the touch point. We slow down the cat when it gets within a distance of MaxCatSpeed to the touch point.
  544. float smoothStop = 1;
  545. #if IPHONE
  546. // check to see if the user wants to move the cat. we'll create a vector
  547. // called catMovement, which will store the sum of all the user's inputs.
  548. catMovement = currentGamePadState.ThumbSticks.Left;
  549. // flip y: on the thumbsticks, down is -1, but on the screen, down is bigger
  550. // numbers.
  551. catMovement.Y *= -1;
  552. if (currentKeyboardState.IsKeyDown (Keys.Left) ||
  553. currentGamePadState.DPad.Left == ButtonState.Pressed) {
  554. catMovement.X -= 1.0f;
  555. }
  556. if (currentKeyboardState.IsKeyDown (Keys.Right) ||
  557. currentGamePadState.DPad.Right == ButtonState.Pressed) {
  558. catMovement.X += 1.0f;
  559. }
  560. if (currentKeyboardState.IsKeyDown (Keys.Up) ||
  561. currentGamePadState.DPad.Up == ButtonState.Pressed) {
  562. catMovement.Y -= 1.0f;
  563. }
  564. if (currentKeyboardState.IsKeyDown (Keys.Down) ||
  565. currentGamePadState.DPad.Down == ButtonState.Pressed) {
  566. catMovement.Y += 1.0f;
  567. }
  568. TouchCollection currentTouchCollection = TouchPanel.GetState();
  569. if (currentTouchCollection != null )
  570. {
  571. if (currentTouchCollection.Count > 0)
  572. {
  573. Vector2 touchPosition = currentTouchCollection[0].Position;
  574. if (touchPosition != catPosition)
  575. {
  576. catMovement = touchPosition - catPosition;
  577. float delta = MaxCatSpeed - MathHelper.Clamp(catMovement.Length(), 0, MaxCatSpeed);
  578. smoothStop = 1 - delta / MaxCatSpeed;
  579. }
  580. }
  581. }
  582. #else
  583. if (currentKeyboardState.IsKeyDown (Keys.Left)) {
  584. catMovement.X -= 1.0f;
  585. }
  586. if (currentKeyboardState.IsKeyDown (Keys.Right)) {
  587. catMovement.X += 1.0f;
  588. }
  589. if (currentKeyboardState.IsKeyDown (Keys.Up)) {
  590. catMovement.Y -= 1.0f;
  591. }
  592. if (currentKeyboardState.IsKeyDown (Keys.Down)) {
  593. catMovement.Y += 1.0f;
  594. }
  595. Vector2 mousePosition = new Vector2 (currentMouseState.X, currentMouseState.Y);
  596. if (currentMouseState.LeftButton == ButtonState.Pressed && mousePosition != catPosition) {
  597. catMovement = mousePosition - catPosition;
  598. float delta = MaxCatSpeed - MathHelper.Clamp (catMovement.Length (), 0, MaxCatSpeed);
  599. smoothStop = 1 - delta / MaxCatSpeed;
  600. }
  601. #endif
  602. // normalize the user's input, so the cat can never be going faster than
  603. // CatSpeed.
  604. if (catMovement != Vector2.Zero) {
  605. catMovement.Normalize ();
  606. }
  607. catPosition += catMovement * MaxCatSpeed * smoothStop;
  608. }
  609. #endregion
  610. }
  611. }