Subdomain Posts
Python | 5 days ago
None | 5 days ago
None | 17 days ago
REG | 18 days ago
None | 21 days ago
None | 27 days ago
None | 27 days ago
None | 28 days ago
Recent Posts
None | 2 min ago
None | 2 min ago
HTML | 2 min ago
HTML | 3 min ago
C | 3 min ago
None | 3 min ago
None | 3 min ago
None | 3 min ago
What is pastebin?
Pastebin is a website that hosts all your text & code on dedicated servers for easy sharing.
learn more...
Domain Reports
Please check out our new and improved Firefox Add-on. hide message
By R Forrest on the 8th of Feb 2010 02:37:41 PM Download | Raw | Embed | Report
  1.  
  2. #region Using Statements
  3. using System;
  4. using Microsoft.Xna.Framework;
  5. using Microsoft.Xna.Framework.Content;
  6. using Microsoft.Xna.Framework.Graphics;
  7. using Microsoft.Xna.Framework.Input;
  8. #endregion
  9.  
  10. namespace HeightmapCollision
  11. {
  12.     /// <summary>
  13.     /// Sample showing how to use get the height of a programmatically generated
  14.     /// heightmap.
  15.     /// </summary>
  16.     public class ZombieIsland : Microsoft.Xna.Framework.Game
  17.     {
  18.         #region Constants
  19.  
  20.         // This constant controls how quickly the sphere can move forward and backward
  21.         const float SphereVelocity = 2;
  22.  
  23.         // how quickly the sphere can turn from side to side
  24.         const float SphereTurnSpeed = .025f;
  25.  
  26.         // the radius of the sphere. We'll use this to keep the sphere above the ground,
  27.         // and when computing how far the sphere has rolled.
  28.         const float SphereRadius = 12.0f;
  29.  
  30.         // This vector controls how much the camera's position is offset from the
  31.         // sphere. This value can be changed to move the camera further away from or
  32.         // closer to the sphere.
  33.         readonly Vector3 CameraPositionOffset = new Vector3(0, 40, 15);
  34.         readonly Vector3 GunPositionOffset = new Vector3(0, 25, -15);
  35.  
  36.         // This value controls the point the camera will aim at. This value is an offset
  37.         // from the sphere's position.
  38.         readonly Vector3 CameraTargetOffset = new Vector3(0, 25, -15);
  39.  
  40.  
  41.         #endregion
  42.  
  43.         #region Fields
  44.  
  45.  
  46.         GraphicsDeviceManager graphics;
  47.  
  48.         GameObject terrain = new GameObject();
  49.  
  50.        
  51.  
  52.         Matrix projectionMatrix;
  53.         Matrix viewMatrix;
  54.  
  55.         const int numbullets = 6;
  56.         GameObject[] bullets;
  57.         GameObject gun1 = new GameObject();
  58.  
  59.         Vector3 spherePosition;
  60.         //Vector3 sphereRotation;
  61.         float sphereFacingDirection;
  62.         Matrix sphereRollingMatrix = Matrix.Identity;
  63.  
  64.         GameObject sphere = new GameObject();
  65.  
  66.         HeightMapInfo heightMapInfo;
  67.  
  68.        
  69.  
  70.  
  71.         #endregion
  72.  
  73.         #region Initialization
  74.  
  75.  
  76.         public ZombieIsland()
  77.         {
  78.             graphics = new GraphicsDeviceManager(this);
  79.             Content.RootDirectory = "Content";
  80.  
  81.             //graphics.PreferredBackBufferWidth = 853;
  82.             //graphics.PreferredBackBufferHeight = 480;
  83.         }
  84.  
  85.         protected override void Initialize()
  86.         {
  87.             // now that the GraphicsDevice has been created, we can calculate the
  88.             // aspect ratio ...
  89.             float aspectRatio = graphics.GraphicsDevice.Viewport.Width /
  90.                 (float)graphics.GraphicsDevice.Viewport.Height;
  91.  
  92.             // ... and use that value to create the projection matrix.
  93.             projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
  94.                 MathHelper.ToRadians(45.0f), aspectRatio, 1f, 10000);
  95.  
  96.             base.Initialize();
  97.         }
  98.  
  99.  
  100.         /// <summary>
  101.         /// Load your graphics content.
  102.         /// </summary>
  103.         protected override void LoadContent()
  104.         {
  105.             terrain.model = Content.Load<Model>("terrain");
  106.  
  107.             // The terrain processor attached a HeightMapInfo to the terrain model's
  108.             // Tag. We'll save that to a member variable now, and use it to
  109.             // calculate the terrain's heights later.
  110.             heightMapInfo = terrain.model.Tag as HeightMapInfo;
  111.             if (heightMapInfo == null)
  112.             {
  113.                 string message = "The terrain model did not have a HeightMapInfo " +
  114.                     "object attached. Are you sure you are using the " +
  115.                     "TerrainProcessor?";
  116.                 throw new InvalidOperationException(message);
  117.             }
  118.  
  119.            // sphere = Content.Load<Model>("gun1");
  120.            // sphereRotation = new Vector3(0, -300, 0);
  121.  
  122.             gun1.model = Content.Load<Model>("gun1");
  123.             gun1.rotation = new Vector3(0, -300, 0);
  124.             gun1.position = spherePosition;
  125.  
  126.             bullets = new GameObject[numbullets];
  127.             for (int i = 0; i < numbullets; i++)
  128.             {
  129.                 bullets[i] = new GameObject();
  130.                 bullets[i].model = Content.Load<Model>("missile");
  131.                 bullets[i].scale = 3.0f;
  132.             }
  133.         }
  134.  
  135.  
  136.         #endregion
  137.  
  138.         #region Update and Draw
  139.  
  140.  
  141.         /// <summary>
  142.         /// Allows the game to run logic.
  143.         /// </summary>
  144.         protected override void Update(GameTime gameTime)
  145.         {
  146.             HandleInput();
  147.  
  148.             UpdateCamera();
  149.  
  150.             base.Update(gameTime);
  151.         }
  152.  
  153.         /// <summary>
  154.         /// this function will calculate the camera's position and the position of
  155.         /// its target. From those, we'll update the viewMatrix.
  156.         /// </summary>
  157.         private void UpdateCamera()
  158.         {
  159.             // The camera's position depends on the sphere's facing direction: when the
  160.             // sphere turns, the camera needs to stay behind it. So, we'll calculate a
  161.             // rotation matrix using the sphere's facing direction, and use it to
  162.             // transform the two offset values that control the camera.
  163.             Matrix cameraFacingMatrix = Matrix.CreateRotationY(sphereFacingDirection);
  164.             Vector3 positionOffset = Vector3.Transform(CameraPositionOffset,
  165.                 cameraFacingMatrix);
  166.             Vector3 targetOffset = Vector3.Transform(CameraTargetOffset,
  167.                 cameraFacingMatrix);
  168.  
  169.             // once we've transformed the camera's position offset vector, it's easy to
  170.             // figure out where we think the camera should be.
  171.             Vector3 cameraPosition = spherePosition + positionOffset;
  172.  
  173.             // We don't want the camera to go beneath the heightmap, so if the camera is
  174.             // over the terrain, we'll move it up.
  175.             if (heightMapInfo.IsOnHeightmap(cameraPosition))
  176.             {
  177.                 // we don't want the camera to go beneath the terrain's height +
  178.                 // a small offset.
  179.                 float minimumHeight =
  180.                     heightMapInfo.GetHeight(cameraPosition) + CameraPositionOffset.Y;
  181.  
  182.                 if (cameraPosition.Y < minimumHeight)
  183.                 {
  184.                     cameraPosition.Y = minimumHeight;
  185.                 }
  186.             }
  187.  
  188.             if (heightMapInfo.IsOnHeightmap(spherePosition))
  189.             {
  190.                 // we don't want the camera to go beneath the terrain's height +
  191.                 // a small offset.
  192.                 float minimumHeight =
  193.                     heightMapInfo.GetHeight(spherePosition) + GunPositionOffset.Y;
  194.  
  195.                 if (spherePosition.Y < minimumHeight)
  196.                 {
  197.                     spherePosition.Y = minimumHeight;
  198.                 }
  199.             }
  200.  
  201.  
  202.             // next, we need to calculate the point that the camera is aiming it. That's
  203.             // simple enough - the camera is aiming at the sphere, and has to take the
  204.             // targetOffset into account.
  205.             Vector3 cameraTarget = spherePosition + targetOffset;
  206.  
  207.  
  208.             // with those values, we'll calculate the viewMatrix.
  209.             viewMatrix = Matrix.CreateLookAt(cameraPosition,
  210.                                               cameraTarget,
  211.                                               Vector3.Up);
  212.         }
  213.  
  214.  
  215.         /// <summary>
  216.         /// This is called when the game should draw itself.
  217.         /// </summary>
  218.         protected override void Draw(GameTime gameTime)
  219.         {
  220.             GraphicsDevice device = graphics.GraphicsDevice;
  221.  
  222.             device.Clear(Color.Black);
  223.  
  224.             DrawGameObject(terrain, Matrix.Identity);
  225.  
  226.             DrawGameObject(sphere, sphereRollingMatrix *
  227.                 Matrix.CreateTranslation(spherePosition));
  228.  
  229.             // If there was any alpha blended translucent geometry in
  230.             // the scene, that would be drawn here.
  231.  
  232.             base.Draw(gameTime);
  233.         }
  234.  
  235.  
  236.         /// <summary>
  237.         /// Helper for drawing the terrain model.
  238.         /// </summary>
  239.         void DrawGameObject(GameObject gameobject, Matrix worldMatrix)
  240.  
  241.         {
  242.            
  243.             gameobject.model.CopyAbsoluteBoneTransformsTo(gameobject.boneTransforms);
  244.  
  245.             foreach (ModelMesh mesh in gameobject.model.Meshes)
  246.  
  247.             {
  248.                 foreach (BasicEffect effect in mesh.Effects)
  249.                 {
  250.                     effect.EnableDefaultLighting();
  251.                     effect.PreferPerPixelLighting = true;
  252.                     effect.World = Matrix.CreateFromYawPitchRoll(
  253.                         gameobject.rotation.X,
  254.                         gameobject.rotation.Y,
  255.                         gameobject.rotation.Z) *
  256.                         Matrix.CreateScale(gameobject.scale) *
  257.                        Matrix.CreateTranslation(gameobject.position);
  258.                     effect.World = gameobject.boneTransforms[mesh.ParentBone.Index] * worldMatrix;
  259.                     effect.FogEnabled = true;
  260.                     effect.FogColor = Vector3.Zero;
  261.                     effect.FogStart = 1000;
  262.                     effect.FogEnd = 3200;
  263.                     effect.World = gameobject.boneTransforms[mesh.ParentBone.Index] * worldMatrix;
  264.                     effect.View = viewMatrix;
  265.                     effect.Projection = projectionMatrix;
  266.  
  267.                     effect.EnableDefaultLighting();
  268.                     effect.PreferPerPixelLighting = true;
  269.  
  270.                     // Set the fog to match the black background color
  271.                     effect.FogEnabled = true;
  272.                     effect.FogColor = Vector3.Zero;
  273.                     effect.FogStart = 1000;
  274.                     effect.FogEnd = 3200;
  275.                 }
  276.                 mesh.Draw();
  277.             }
  278.  
  279.         }
  280.  
  281.         //void DrawModel(Model model, Matrix worldMatrix)
  282.        // {
  283.             //Matrix[] boneTransforms = new Matrix[model.Bones.Count];
  284.             //model.CopyAbsoluteBoneTransformsTo(boneTransforms);
  285.  
  286.            // foreach (ModelMesh mesh in model.Meshes)
  287.             //{
  288.                 //foreach (BasicEffect effect in mesh.Effects)
  289.                // {
  290.                   //  effect.World = boneTransforms[mesh.ParentBone.Index] * worldMatrix;
  291.                  //   effect.View = viewMatrix;
  292.                  //   effect.Projection = projectionMatrix;
  293.  
  294.                  //   effect.EnableDefaultLighting();
  295.                   //  effect.PreferPerPixelLighting = true;
  296.  
  297.                     // Set the fog to match the black background color
  298.                  //   effect.FogEnabled = true;
  299.                  //   effect.FogColor = Vector3.Zero;
  300.                 //    effect.FogStart = 1000;
  301.                 //    effect.FogEnd = 3200;
  302.               //  }
  303.  
  304.             //    mesh.Draw();
  305.           //  }
  306.        // }
  307.  
  308.  
  309.         #endregion
  310.  
  311.         #region Handle Input
  312.  
  313.  
  314.  
  315.         /// <summary>
  316.         /// Handles input for quitting the game.
  317.         /// </summary>
  318.         private void HandleInput()
  319.         {
  320.             KeyboardState currentKeyboardState = Keyboard.GetState();
  321.             GamePadState currentGamePadState = GamePad.GetState(PlayerIndex.One);
  322.  
  323.             // Check for exit.
  324.             if (currentKeyboardState.IsKeyDown(Keys.Escape) ||
  325.                 currentGamePadState.Buttons.Back == ButtonState.Pressed)
  326.             {
  327.                 Exit();
  328.             }
  329.  
  330.             // Now move the sphere. First, we want to check to see if the sphere should
  331.             // turn. turnAmount will be an accumulation of all the different possible
  332.             // inputs.
  333.             float turnAmount = -currentGamePadState.ThumbSticks.Left.X;
  334.             if (currentKeyboardState.IsKeyDown(Keys.A) ||
  335.                 currentKeyboardState.IsKeyDown(Keys.Left) ||
  336.                 currentGamePadState.DPad.Left == ButtonState.Pressed)
  337.             {
  338.                 turnAmount += 1;
  339.             }
  340.             if (currentKeyboardState.IsKeyDown(Keys.D) ||
  341.                 currentKeyboardState.IsKeyDown(Keys.Right) ||
  342.                 currentGamePadState.DPad.Right == ButtonState.Pressed)
  343.             {
  344.                 turnAmount -= 1;
  345.             }
  346.  
  347.             // clamp the turn amount between -1 and 1, and then use the finished
  348.             // value to turn the sphere.
  349.             turnAmount = MathHelper.Clamp(turnAmount, -1, 1);
  350.             sphereFacingDirection += turnAmount * SphereTurnSpeed;
  351.  
  352.  
  353.             // Next, we want to move the sphere forward or back. to do this,
  354.             // we'll create a Vector3 and modify use the user's input to modify the Z
  355.             // component, which corresponds to the forward direction.
  356.             Vector3 movement = Vector3.Zero;
  357.             movement.Z = -currentGamePadState.ThumbSticks.Left.Y;
  358.  
  359.             if (currentKeyboardState.IsKeyDown(Keys.W) ||
  360.                 currentKeyboardState.IsKeyDown(Keys.Up) ||
  361.                 currentGamePadState.DPad.Up == ButtonState.Pressed)
  362.             {
  363.                 movement.Z = -1;
  364.             }
  365.             if (currentKeyboardState.IsKeyDown(Keys.S) ||
  366.                 currentKeyboardState.IsKeyDown(Keys.Down) ||
  367.                 currentGamePadState.DPad.Down == ButtonState.Pressed)
  368.             {
  369.                 movement.Z = 1;
  370.             }
  371.  
  372.             // next, we'll create a rotation matrix from the sphereFacingDirection, and
  373.             // use it to transform the vector. If we didn't do this, pressing "up" would
  374.             // always move the ball along +Z. By transforming it, we can move in the
  375.             // direction the sphere is "facing."
  376.             Matrix sphereFacingMatrix = Matrix.CreateRotationY(sphereFacingDirection);
  377.             Vector3 velocity = Vector3.Transform(movement, sphereFacingMatrix);
  378.             velocity *= SphereVelocity;
  379.  
  380.             // Now we know how much the user wants to move. We'll construct a temporary
  381.             // vector, newSpherePosition, which will represent where the user wants to
  382.             // go. If that value is on the heightmap, we'll allow the move.
  383.             Vector3 newSpherePosition = spherePosition + velocity;
  384.             if (heightMapInfo.IsOnHeightmap(newSpherePosition))
  385.             {
  386.                 // finally, we need to see how high the terrain is at the sphere's new
  387.                 // position. GetHeight will give us that information, which is offset by
  388.                 // the size of the sphere. If we didn't offset by the size of the
  389.                 // sphere, it would be drawn halfway through the world, which looks
  390.                 // a little odd.
  391.                 newSpherePosition.Y = heightMapInfo.GetHeight(newSpherePosition) +
  392.                     SphereRadius;
  393.             }
  394.             else
  395.             {
  396.                 newSpherePosition = spherePosition;
  397.             }
  398.  
  399.             // now we need to roll the ball "forward." to do this, we first calculate
  400.             // how far it has moved.
  401.             float distanceMoved = Vector3.Distance(spherePosition, newSpherePosition);
  402.  
  403.             // The length of an arc on a circle or sphere is defined as L = theta * r,
  404.             // where theta is the angle that defines the arc, and r is the radius of
  405.             // the circle.
  406.             // we know L, that's the distance the sphere has moved. we know r, that's
  407.             // our constant "sphereRadius". We want to know theta - that will tell us
  408.             // how much to rotate the sphere. we rearrange the equation to get...
  409.             float theta = distanceMoved / SphereRadius;
  410.  
  411.             // now that we know how much to rotate the sphere, we have to figure out
  412.             // whether it will roll forward or backward. We'll base this on the user's
  413.             // input.
  414.             int rollDirection = movement.Z > 0 ? 1 : -1;
  415.  
  416.             // finally, we'll roll it by rotating around the sphere's "right" vector.
  417.            // sphereRollingMatrix *= Matrix.CreateFromAxisAngle(sphereFacingMatrix.Right,
  418.             //    theta * rollDirection);
  419.  
  420.             // once we've finished all computations, we can set spherePosition to the
  421.             // new position that we calculated.
  422.             spherePosition = newSpherePosition;
  423.         }
  424.  
  425.         #endregion
  426.     }
  427.  
  428.  
  429.     #region Entry Point
  430.  
  431.     /// <summary>
  432.     /// The main entry point for the application.
  433.     /// </summary>
  434.     static class Program
  435.     {
  436.         static void Main()
  437.         {
  438.             using (ZombieIsland game = new ZombieIsland())
  439.             {
  440.                 game.Run();
  441.             }
  442.         }
  443.     }
  444.  
  445.     #endregion
  446. }
  447.  
  448.  
  449. -------
  450. GameObject.cs
  451. -------
  452. using Microsoft.Xna.Framework.Content;
  453. using Microsoft.Xna.Framework.GamerServices;
  454. using Microsoft.Xna.Framework.Graphics;
  455. using Microsoft.Xna.Framework.Input;
  456. using Microsoft.Xna.Framework.Media;
  457. using Microsoft.Xna.Framework.Net;
  458. using Microsoft.Xna.Framework.Storage;
  459. using Microsoft.Xna.Framework;
  460.  
  461. namespace HeightmapCollision
  462. {
  463.     class GameObject
  464.     {
  465.         GameObject gameobject;
  466.         public Model model = null;
  467.         public Vector3 position = Vector3.Zero;
  468.         public Vector3 rotation = Vector3.Zero;
  469.         public float scale = 1.0f;
  470.         public Vector3 velocity = Vector3.Zero;
  471.         public bool alive = false;
  472.  
  473.         public Matrix[] boneTransforms;
  474.  
  475.  
  476.         public GameObject()
  477.         {
  478.             gameobject = new GameObject();
  479.             boneTransforms = new Matrix[gameobject.model.Bones.Count];
  480.          
  481.            
  482.         }
  483.  
  484.     }
  485. }
Submit a correction or amendment below. Make A New Post
To highlight particular lines, prefix each line with @h@
Syntax highlighting:
Post expiration:
Post exposure:
Name / Title:
Email: