void Setup(HeightMapInfo heightMapInfo, Vector2 shift) { // A dummy. The physics object uses its position to get draw pos Body = new Body(); CollisionSkin = new CollisionSkin(null); info = heightMapInfo; Array2D field = new Array2D(heightMapInfo.Heights.GetUpperBound(0), heightMapInfo.Heights.GetUpperBound(1)); for (int x = 0; x < heightMapInfo.Heights.GetUpperBound(0); ++x) { for (int z = 0; z < heightMapInfo.Heights.GetUpperBound(1); ++z) { field.SetAt(x, z, heightMapInfo.Heights[x, z]); } } // Move dummy body. The body isn't connected to the collision skin. // But the base class should know where to draw the model. Body.MoveTo(new Vector3(shift.X, 0, shift.Y), Matrix.Identity); CollisionSkin.AddPrimitive(new Heightmap(field, shift.X, shift.Y, 1, 1), new MaterialProperties(0.7f, 0.7f, 0.6f)); PhysicsSystem.CurrentPhysicsSystem.CollisionSystem.AddCollisionSkin(CollisionSkin); }
public HeightmapObject(Game game, Model model, Vector2 shift) : base(game, model) { body = new Body(); // just a dummy. The PhysicObject uses its position to get the draw pos collision = new CollisionSkin(null); HeightMapInfo heightMapInfo = model.Tag as HeightMapInfo; Array2D field = new Array2D(heightMapInfo.heights.GetUpperBound(0), heightMapInfo.heights.GetUpperBound(1)); for (int x = 0; x < heightMapInfo.heights.GetUpperBound(0); x++) { for (int z = 0; z < heightMapInfo.heights.GetUpperBound(1); z++) { field.SetAt(x, z, heightMapInfo.heights[x, z]); } } // move the body. The body (because its not connected to the collision // skin) is just a dummy. But the base class shoudl know where to // draw the model. body.MoveTo(new Vector3(shift.X, 0, shift.Y), Matrix.Identity); collision.AddPrimitive(new Heightmap(field, shift.X, shift.Y, 1, 1), new MaterialProperties(0.7f, 0.7f, 0.6f)); PhysicsSystem.CurrentPhysicsSystem.CollisionSystem.AddCollisionSkin(collision); }
public HeightmapObject(Model model, Vector2 shift, Vector3 position) : base() { //body = new Body(); // just a dummy. The PhysicObject uses its position to get the draw pos //Skin = new CollisionSkin(null); HeightMapInfo heightMapInfo = model.Tag as HeightMapInfo; Array2D field = new Array2D(heightMapInfo.heights.GetLength(0), heightMapInfo.heights.GetLength(1)); for (int x = 0; x < heightMapInfo.heights.GetLength(0); x++) { for (int z = 0; z < heightMapInfo.heights.GetLength(1); z++) { field.SetAt(x, z, heightMapInfo.heights[x, z]); } } // move the body. The body (because its not connected to the collision // skin) is just a dummy. But the base class shoudl know where to // draw the model. //body.MoveTo(new Vector3(shift.X,0,shift.Y), Matrix.Identity); //Skin.AddPrimitive(new Heightmap(field, shift.X, shift.Y, heightMapInfo.terrainScale, heightMapInfo.terrainScale), new MaterialProperties(0.7f, 0.7f, 0.6f)); //PhysicsSystem.CurrentPhysicsSystem.CollisionSystem.AddCollisionSkin(Skin); CommonInit(position, new Vector3(1, 1, 1), model, false, 0); }
//PUBLIC METHODS /// <summary> /// Loads the specified heightmap from the a file. /// </summary> /// <param name="filename">filename to load</param> /// <param name="info">Heightmap info</param> /// <param name="heightmap">out heightmap</param> /// <returns>True/False heightmap can be loaded</returns> public static bool LoadFromFile(string filename, HeightMapInfo info, out HeightMap heightmap) { bool result = false; FileStream filestream = null; try { //OPEN THE FILESTREAM filestream = new FileStream(filename, FileMode.Open, FileAccess.Read); BinaryReader reader = new BinaryReader(filestream); //GENERATE NEW HEIGHTMAP HeightMap hmap = new HeightMap(); hmap.info = info; //GENERATE MAX X, Y VALUES int MaxX = hmap.info.size; int MaxY = hmap.info.size; //GENERATE X/Y ARRAY FOR hmap.HeightData = new float[MaxX, MaxY]; //READ ALL Z COORDS float size = (hmap.info.size / 2); for (int y = 0; y < MaxY; y++) { for (int x = 0; x < MaxX; x++) { hmap.HeightData[x, y] = (float)(((float)reader.ReadUInt16() - 32768) / 32768) * size; } } //CLOSE DOWN RESOURCES reader.Close(); filestream.Close(); heightmap = hmap; result = true; } catch (IOException) { //A IO-EXCEPTION OCCURED Trace.TraceError("Cannot load heightmap from file: {0}", filename); heightmap = null; result = false; } catch (OutOfMemoryException) { //WE RUN OUT OF MEMORY WHILE LOADING A MAP, THIS CAN BE THE RESULT OF CORRUPT MEMORY Trace.TraceError("Ran out of memory when attempting to load: {0}", filename); heightmap = null; result = false; } finally { //CLOSE DOWN RESOURCES if (filestream != null) filestream.Close(); } return result; }
protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); music = Content.Load<Song>("backgroundMusic"); terrain = Content.Load<Model>("terrain"); // The terrain processor attached a HeightMapInfo to the terrain model's heightMapInfo = terrain.Tag as HeightMapInfo; if (heightMapInfo == null) { string message = "The terrain model did not have a HeightMapInfo " + "object attached. Are you sure you are using the " + "TerrainProcessor?"; throw new InvalidOperationException(message); } MediaPlayer.Play(music); MediaPlayer.IsRepeating = true; //loop song tank.LoadContent(Content); }
public override void Update(GameTime gameTime, HeightMapInfo heightMapInfo) { this._gameTime = gameTime; var time = (float)gameTime.TotalGameTime.TotalSeconds; if (!_isDead) this.RotationZ = time * RocketRotationSpeed; if (_canCollide) this.UpdateCollision(gameTime, heightMapInfo); if (!_isDead) { _speed = RocketSpeed; AdjustToHeightMap(gameTime, heightMapInfo); } else { _speed = 0; } this.UpdateBoundingSphere(); this.Moved = false; }
// End-------------------------------------------------------------- /// <summary> /// BOT COLLISION /// </summary> public static bool isBotValidMove(HydroBot hydroBot, Vector3 futurePosition, SwimmingObject[] enemies,int enemiesAmount, SwimmingObject[] fish, int fishAmount, HeightMapInfo heightMapInfo) { BoundingSphere futureBoundingSphere = hydroBot.BoundingSphere; futureBoundingSphere.Center.X = futurePosition.X; futureBoundingSphere.Center.Z = futurePosition.Z; //Don't allow off-terrain driving if (isOutOfMap(futurePosition, hydroBot.MaxRangeX, hydroBot.MaxRangeZ, futureBoundingSphere)) { return false; } //in supersonice mode, you knock and you stun the enemies if (HydroBot.supersonicMode == true) { if (isBotVsBarrierCollision(futureBoundingSphere, fish, fishAmount)) return false; return true; } //else don't allow driving through an enemy if (isBotVsBarrierCollision(futureBoundingSphere, enemies, enemiesAmount)) { return false; } if (isBotVsBarrierCollision(futureBoundingSphere, fish, fishAmount)) { return false; } //if (heightMapInfo != null) //{ // if (heightMapInfo.GetHeight(futurePosition) >= -10) // return false; //} return true; }
void SetUpTerrain() { #region Loading Height Data Texture2D heightMap = Content.Load<Texture2D>("Land"); float minimumHeight = float.MaxValue; float maximumHeight = float.MinValue; float heightRange = 20; waterHeight = heightRange * 0.10f; terrainWidth = heightMap.Width; terrainLength = heightMap.Height; Color[] heightMapColors = new Color[terrainWidth * terrainLength]; heightMap.GetData(heightMapColors); heightData = new float[terrainWidth, terrainLength]; for (int x = 0; x < terrainWidth; x++) for (int y = 0; y < terrainLength; y++) { heightData[x, y] = heightMapColors[x + y * terrainWidth].R; if (heightData[x, y] < minimumHeight) minimumHeight = heightData[x, y]; if (heightData[x, y] > maximumHeight) maximumHeight = heightData[x, y]; } for (int x = 0; x < terrainWidth; x++) for (int y = 0; y < terrainLength; y++) heightData[x, y] = (heightData[x, y] - minimumHeight) / (maximumHeight - minimumHeight) * heightRange; #endregion #region Generating Vertices terrainVertices = new VertexMultitextured[terrainWidth * terrainLength]; for (int x = 0; x < terrainWidth; x++) { for (int y = 0; y < terrainLength; y++) { float height = heightData[x, y]; terrainVertices[x + y * terrainWidth].Position = new Vector3(x, height, y); terrainVertices[x + y * terrainWidth].TextureCoordinate.X = (float)x / 30.0f; terrainVertices[x + y * terrainWidth].TextureCoordinate.Y = (float)y / 30.0f; terrainVertices[x + y * terrainWidth].TexWeights.X = MathHelper.Clamp(1.0f - Math.Abs(height - 0) / (heightRange / 4), 0, 1);//sand terrainVertices[x + y * terrainWidth].TexWeights.Y = MathHelper.Clamp(1.0f - Math.Abs(height - heightRange / 3) / (heightRange / 4), 0, 1);//grass terrainVertices[x + y * terrainWidth].TexWeights.Z = MathHelper.Clamp(1.0f - Math.Abs(height - 2 * heightRange / 3) / (heightRange / 4), 0, 1);//rock terrainVertices[x + y * terrainWidth].TexWeights.W = MathHelper.Clamp(1.0f - Math.Abs(height - heightRange) / (heightRange / 4), 0, 1);//snow float total = terrainVertices[x + y * terrainWidth].TexWeights.X; total += terrainVertices[x + y * terrainWidth].TexWeights.Y; total += terrainVertices[x + y * terrainWidth].TexWeights.Z; total += terrainVertices[x + y * terrainWidth].TexWeights.W; terrainVertices[x + y * terrainWidth].TexWeights.X /= total; terrainVertices[x + y * terrainWidth].TexWeights.Y /= total; terrainVertices[x + y * terrainWidth].TexWeights.Z /= total; terrainVertices[x + y * terrainWidth].TexWeights.W /= total; } } #endregion #region Generating Indices terrainIndices = new int[(terrainWidth - 1) * (terrainLength - 1) * 6]; int counter = 0; for (int y = 0; y < terrainLength - 1; y++) { for (int x = 0; x < terrainWidth - 1; x++) { int lowerLeft = x + (y + 1) * terrainWidth; int lowerRight = (x + 1) + (y + 1) * terrainWidth; int topLeft = x + y * terrainWidth; int topRight = (x + 1) + y * terrainWidth; terrainIndices[counter++] = topLeft; terrainIndices[counter++] = lowerRight; terrainIndices[counter++] = lowerLeft; terrainIndices[counter++] = topLeft; terrainIndices[counter++] = topRight; terrainIndices[counter++] = lowerRight; } } #endregion #region Calculating Normals for (int i = 0; i < terrainVertices.Length; i++) terrainVertices[i].Normal = new Vector3(0, 0, 0); for (int i = 0; i < terrainIndices.Length / 3; i++) { int index1 = terrainIndices[i * 3]; int index2 = terrainIndices[i * 3 + 1]; int index3 = terrainIndices[i * 3 + 2]; Vector3 side1 = terrainVertices[index1].Position - terrainVertices[index3].Position; Vector3 side2 = terrainVertices[index1].Position - terrainVertices[index2].Position; Vector3 normal = Vector3.Cross(side1, side2); terrainVertices[index1].Normal += normal; terrainVertices[index2].Normal += normal; terrainVertices[index3].Normal += normal; } for (int i = 0; i < terrainVertices.Length; i++) { terrainVertices[i].Normal.Normalize(); float temp = terrainVertices[i].Normal.Y; temp = MathHelper.Clamp((float)Math.Pow(temp, 2), 0, 1); float mag = terrainVertices[i].TexWeights.Length(); terrainVertices[i].TexWeights.Normalize(); terrainVertices[i].TexWeights *= temp; terrainVertices[i].TexWeights += Vector4.UnitZ * (1 - temp); terrainVertices[i].TexWeights *= mag; } #endregion #region Loading Buffers terrainVertexBuffer = new VertexBuffer(GraphicsDevice, VertexMultitextured.VertexDeclaration, terrainVertices.Length, BufferUsage.WriteOnly); terrainVertexBuffer.SetData(terrainVertices); terrainIndexBuffer = new IndexBuffer(GraphicsDevice, typeof(int), terrainIndices.Length, BufferUsage.WriteOnly); terrainIndexBuffer.SetData(terrainIndices); #endregion #region Water VertexPositionTexture[] waterVertices = new VertexPositionTexture[6]; waterVertices[0] = new VertexPositionTexture(new Vector3(0, waterHeight, terrainLength), new Vector2(0, 1)); waterVertices[2] = new VertexPositionTexture(new Vector3(terrainWidth, waterHeight, 0), new Vector2(1, 0)); waterVertices[1] = new VertexPositionTexture(new Vector3(0, waterHeight, 0), new Vector2(0, 0)); waterVertices[3] = new VertexPositionTexture(new Vector3(0, waterHeight, terrainLength), new Vector2(0, 1)); waterVertices[5] = new VertexPositionTexture(new Vector3(terrainWidth, waterHeight, terrainLength), new Vector2(1, 1)); waterVertices[4] = new VertexPositionTexture(new Vector3(terrainWidth, waterHeight, 0), new Vector2(1, 0)); waterVertexBuffer = new VertexBuffer(GraphicsDevice, VertexPositionTexture.VertexDeclaration, waterVertices.Length, BufferUsage.WriteOnly); waterVertexBuffer.SetData(waterVertices); effect.Parameters["xFogColor0"].SetValue(new Vector4(new Vector3(0.7f), 1)); effect.Parameters["xFogColor1"].SetValue(Color.WhiteSmoke.ToVector4()); effect.Parameters["xWaterBumpMap"].SetValue(waterBumpMap); effect.Parameters["xWaveLength"].SetValue(0.5f); effect.Parameters["xWaveHeight"].SetValue(0.1f); Vector3 windDirection = new Vector3(1, 0, 0); effect.Parameters["xWindForce"].SetValue(7.0f); effect.Parameters["xWindDirection"].SetValue(windDirection); #endregion Vector3[,] normals = new Vector3[terrainWidth, terrainLength]; for (int x = 0; x < terrainWidth; x++) for (int y = 0; y < terrainLength; y++) normals[x, y] = terrainVertices[x + y * terrainWidth].Normal; heightMapInfo = new HeightMapInfo(heightData, normals, 1); }
public void MovePlayer(GamePadState currentGamePadState, KeyboardState currentKeyboardState, HeightMapInfo heightMapInfo) { #region Player Movement float cannonRotateAmount = -currentGamePadState.ThumbSticks.Right.Y * .1f; if (currentKeyboardState.IsKeyDown(Keys.Y)) //|| //currentGamePadState.DPad.Left == ButtonState.Pressed) { cannonRotateAmount += 0.02f; } if (currentKeyboardState.IsKeyDown(Keys.H)) //|| //currentGamePadState.DPad.Left == ButtonState.Pressed) { cannonRotateAmount -= 0.02f; } float newCannonRotate = tank.CannonRotate + cannonRotateAmount; newCannonRotate = MathHelper.Clamp(newCannonRotate, -MathHelper.PiOver4/2.5f , MathHelper.PiOver4/2.5f ); //Code to rotate the turret with the right thumbstick or J button float turretRotateAmount = currentGamePadState.ThumbSticks.Right.X * .1f; if (currentKeyboardState.IsKeyDown(Keys.G)) //|| //currentGamePadState.DPad.Left == ButtonState.Pressed) { turretRotateAmount -= 0.02f; } if (currentKeyboardState.IsKeyDown(Keys.J)) //|| //currentGamePadState.DPad.Left == ButtonState.Pressed) { turretRotateAmount += 0.02f; } float newTurretRotate = tank.TurretRotate + turretRotateAmount; newTurretRotate = MathHelper.Clamp(newTurretRotate, -MathHelper.PiOver2 / 1, MathHelper.PiOver2 / 1); // First, we want to check to see if the tank should turn. turnAmount will // be an accumulation of all the different possible inputs. float turnAmount = -currentGamePadState.ThumbSticks.Left.X; // turn LEFT float steerRotationAmount = currentGamePadState.ThumbSticks.Right.X * .1f; if (currentKeyboardState.IsKeyDown(Keys.Left) || currentGamePadState.DPad.Left == ButtonState.Pressed || currentKeyboardState.IsKeyDown(Keys.A)) { steerRotationAmount -= 0.04f; // player is turning holding Foward button if (currentKeyboardState.IsKeyDown(Keys.Up) || currentGamePadState.DPad.Up == ButtonState.Pressed || currentKeyboardState.IsKeyDown(Keys.W) ) { steerRotationAmount -= 0.05f; turnAmount += 1; } // player is turning holding Bacward button if (currentKeyboardState.IsKeyDown(Keys.Down) || currentGamePadState.DPad.Down == ButtonState.Pressed || currentKeyboardState.IsKeyDown(Keys.S)) { steerRotationAmount -= 0.05f; turnAmount -= 1; } } if (currentKeyboardState.IsKeyDown(Keys.D) || // turn RIGHT currentKeyboardState.IsKeyDown(Keys.Right) || currentGamePadState.DPad.Right == ButtonState.Pressed) { steerRotationAmount += 0.04f; // player is turning holding Foward button if (currentKeyboardState.IsKeyDown(Keys.Up) || currentGamePadState.DPad.Up == ButtonState.Pressed || currentKeyboardState.IsKeyDown(Keys.W)) { steerRotationAmount += 0.05f; turnAmount -= 1; } // player is turning holding Bacward button if (currentKeyboardState.IsKeyDown(Keys.Down) || currentGamePadState.DPad.Down == ButtonState.Pressed || currentKeyboardState.IsKeyDown(Keys.S)) { steerRotationAmount += 0.05f; turnAmount += 1; } } // clamp the turn amount between -1 and 1, and then use the finished // value to turn the tank. turnAmount = MathHelper.Clamp(turnAmount, -1, 1); tank.FacingDirection += turnAmount * TankTurnSpeed; // Next, we want to move the tank forward or back. to do this, // we'll create a Vector3 and modify use the user's input to modify the Z // component, which corresponds to the forward direction. Vector3 movement = Vector3.Zero; movement.Z = -currentGamePadState.ThumbSticks.Left.Y; if (currentKeyboardState.IsKeyDown(Keys.Up) || currentGamePadState.DPad.Up == ButtonState.Pressed || // FOWARD currentKeyboardState.IsKeyDown(Keys.W)) { movement.Z = -1; // case when player is turning holding Foward button if (currentKeyboardState.IsKeyUp(Keys.Left) || currentKeyboardState.IsKeyUp(Keys.A) || currentGamePadState.DPad.Right == ButtonState.Released || currentKeyboardState.IsKeyUp(Keys.Right) || currentKeyboardState.IsKeyUp(Keys.D) || currentGamePadState.DPad.Left == ButtonState.Released ) { if (tank.SteerRotationValue > 0 & tank.SteerRotationValue != 0) steerRotationAmount -= 0.05f; if (tank.SteerRotationValue < 0 & tank.SteerRotationValue != 0) steerRotationAmount += 0.05f; } } if (currentKeyboardState.IsKeyDown(Keys.Down) || // BACKWARD currentKeyboardState.IsKeyDown(Keys.S) || currentGamePadState.DPad.Down == ButtonState.Pressed) { movement.Z = 0.7f; // case when player is turning holding Bacward button if (currentKeyboardState.IsKeyUp(Keys.Left) || currentKeyboardState.IsKeyUp(Keys.A) || currentGamePadState.DPad.Right == ButtonState.Released || currentKeyboardState.IsKeyUp(Keys.Right) || currentKeyboardState.IsKeyUp(Keys.D) || currentGamePadState.DPad.Left == ButtonState.Released ) { if (tank.SteerRotationValue > 0 & tank.SteerRotationValue != 0) steerRotationAmount -= 0.05f; if (tank.SteerRotationValue < 0 & tank.SteerRotationValue != 0) steerRotationAmount += 0.05f; } } if (currentKeyboardState.IsKeyDown(Keys.LeftShift)) { movement *= 2; if (currentKeyboardState.IsKeyDown(Keys.Down) || currentKeyboardState.IsKeyDown(Keys.Up) || currentKeyboardState.IsKeyDown(Keys.S) || currentKeyboardState.IsKeyDown(Keys.W)) boost = true; } else { boost = false; } // turning tanks front wheels float newSteerRotationValue = tank.SteerRotationValue + steerRotationAmount; newSteerRotationValue = MathHelper.Clamp(newSteerRotationValue, -MathHelper.PiOver4, MathHelper.PiOver4); #endregion // next, we'll create a rotation matrix from the direction the tank is // facing, and use it to transform the vector. //tank.Orientation = Matrix.CreateRotationY(tank.FacingDirection); Vector3 velocity = Vector3.Transform(movement, tank.Orientation); velocity *= tank.Velocity; // Now we know how much the user wants to move. We'll construct a temporary // vector, newPosition, which will represent where the user wants to go. If // that value is on the heightmap, we'll allow the move. //Vector3 newPosition = tank.Position + velocity; //if (heightMapInfo.IsOnHeightmap(newPosition)) //{ // now that we know we're on the heightmap, we need to know the correct // height and normal at this position. //Vector3 normal; //heightMapInfo.GetHeightAndNormal(newPosition, //out newPosition.Y, out normal); // As discussed in the doc, we'll use the normal of the heightmap // and our desired forward direction to recalculate our orientation // matrix. It's important to normalize, as well. //Matrix orientation = tank.Orientation; //orientation.Up = normal; //orientation.Right = Vector3.Cross(orientation.Forward, orientation.Up); //orientation.Right = Vector3.Normalize(orientation.Right); //orientation.Forward = Vector3.Cross(orientation.Up, orientation.Right); //orientation.Forward = Vector3.Normalize(orientation.Forward); // tank.Orientation = orientation; // now we need to roll the tank's wheels "forward." to do this, we'll // calculate how far they have rolled, and from there calculate how much // they must have rotated. // float distanceMoved = Vector3.Distance(tank.Position, newPosition); // float theta = distanceMoved / tank.TankWheelRadius; // int rollDirection = movement.Z > 0 ? 1 : -1; //tank.wheelRollMatrix *= Matrix.CreateRotationX(theta * rollDirection); tank.cannonMoveMatrix *= Matrix.CreateRotationX((tank.CannonRotate - newCannonRotate)); tank.turretMoveMatrix *= Matrix.CreateRotationY((tank.TurretRotate - newTurretRotate)); tank.steerRotationMatrix *= Matrix.CreateRotationY(tank.SteerRotationValue - newSteerRotationValue); // once we've finished all computations, we can set our position to the // new position that we calculated. //tank.Position = newPosition; tank.TurretRotate = newTurretRotate; tank.CannonRotate = newCannonRotate; tank.SteerRotationValue = newSteerRotationValue; //} }
public HeightMap(HeightMapInfo info) { this.info = info; this.water_level = info.water_level; this.LoadHMap(); }
/// <summary> /// Creates a new heightmap /// </summary> public HeightMap() { this.HeightData = new float[0, 0]; this.info = new HeightMapInfo(); }
protected override void OnCollision(Entity entity, GameTime gameTime, HeightMapInfo heightMapInfo) { if (entity.ModelName.Contains("egg") || entity.ModelName.Contains("stone")) { this.Die(); } }
public static void PlaceStaticObjects(List<StaticObject> staticObjects, List<ShipWreck> shipWrecks, Random random, HeightMapInfo heightMapInfo, int minX, int maxX, int minZ, int maxZ) { Vector3 tempCenter; //place ship wrecks foreach (StaticObject staticObject in staticObjects) { staticObject.Position = GenerateSeaBedRandomPosition(minX, maxX, minZ, maxZ, random, shipWrecks, staticObjects); //ship wreck should not be floating staticObject.Position.Y = heightMapInfo.GetHeight(staticObject.Position); tempCenter = staticObject.BoundingSphere.Center; tempCenter.X = staticObject.Position.X; if (HydroBot.gameMode == GameMode.MainGame || HydroBot.gameMode == GameMode.SurvivalMode) tempCenter.Y = GameConstants.MainGameFloatHeight; else tempCenter.Y = staticObject.Position.Y; tempCenter.Z = staticObject.Position.Z; staticObject.BoundingSphere = new BoundingSphere(tempCenter, staticObject.BoundingSphere.Radius); //staticObject.CalculateBoundingBox(staticObject.scale, staticObject.orientation); //ModifyBoundingBox(ref staticObject.boundingBox, GameConstants.MainGameFloatHeight); } }
protected void UpdateCollision(GameTime gameTime, HeightMapInfo heightMapInfo) { collisionDelay -= gameTime.ElapsedGameTime; if (collisionDelay >= TimeSpan.Zero) { return; } foreach (Entity entity in _screen.CollideableEntites) { if (entity != this && entity.BoundingSphere.Intersects(this.BoundingSphere)) { this.OnCollision(entity, gameTime, heightMapInfo); } } collisionDelay += TimeSpan.FromSeconds(CollisionInterval); }
public static Vector3 createSinkingTrash( ref List<Trash> trashes, ContentManager Content, Random random, List<ShipWreck> shipWrecks, List<StaticObject> staticObjects, List<Factory> factories, ResearchFacility researchFacility, int minX, int maxX, int minZ, int maxZ, float floatHeight, HeightMapInfo heightMapInfo,ref Model bioTrash,ref Model plasticTrash,ref Model nukeTrash, ParticleManagement particleManager) { if (PoseidonGame.playTime.TotalSeconds - lastTrashDrop <= 10) return Vector3.Zero; else lastTrashDrop = PoseidonGame.playTime.TotalSeconds; Vector3 tempCenter; int numTries = 0, xVal, zVal, heightValue; float orientation = random.Next(100); int trash_type = random.Next(50); Trash sinkingTrash; if (trash_type < 30) { sinkingTrash = new Trash(TrashType.biodegradable, particleManager); sinkingTrash.Load(Content,ref bioTrash, orientation); sinkingTrash.sinkingRate = 0.25f; sinkingTrash.sinkingRotationRate = 0.015f; } else if (trash_type < 48) { sinkingTrash = new Trash(TrashType.plastic, particleManager); sinkingTrash.Load(Content,ref plasticTrash, orientation); //nuclear model sinkingTrash.sinkingRate = 0.35f; sinkingTrash.sinkingRotationRate = -0.015f; } else { sinkingTrash = new Trash(TrashType.radioactive, particleManager); sinkingTrash.Load(Content,ref nukeTrash, orientation); //nuclear model sinkingTrash.sinkingRate = 0.6f; sinkingTrash.sinkingRotationRate = 0.025f; } sinkingTrash.sinking = true; sinkingTrash.sinkableTrash = true; do { //positionSign = random.Next(4); xVal = random.Next(0, 2 * maxX) - maxX; zVal = random.Next(0, 2 * maxZ) - maxZ; //switch (positionSign) //{ // case 0: // xVal *= -1; // break; // case 1: // zVal *= -1; // break; // case 2: // xVal *= -1; // zVal *= -1; // break; //} heightValue = (int)heightMapInfo.GetHeight(new Vector3(xVal, 0, zVal)); numTries++; } while (IsSeaBedPlaceOccupied(xVal, GameConstants.MainGameFloatHeight, zVal, 30, shipWrecks, staticObjects, trashes, factories, researchFacility) && numTries < GameConstants.MaxNumTries); sinkingTrash.Position.X = xVal; sinkingTrash.Position.Z = zVal; sinkingTrash.Position.Y = floatHeight+100; sinkingTrash.seaFloorHeight = heightMapInfo.GetHeight(new Vector3(sinkingTrash.Position.X, 0, sinkingTrash.Position.Z));//GameConstants.TrashFloatHeight; tempCenter = sinkingTrash.BoundingSphere.Center; tempCenter.X = sinkingTrash.Position.X; tempCenter.Y = floatHeight; tempCenter.Z = sinkingTrash.Position.Z; sinkingTrash.BoundingSphere = new BoundingSphere(tempCenter,sinkingTrash.BoundingSphere.Radius); trashes.Add(sinkingTrash); //degrade environment HydroBot.currentEnvPoint -= (int)((float)GameConstants.envLossPerTrashAdd / 2); return sinkingTrash.Position; }
public static void placeShipWreck(List<ShipWreck> shipWrecks, List<StaticObject> staticObjects, Random random, HeightMapInfo heightMapInfo, int minX, int maxX, int minZ, int maxZ) { //int min = GameConstants.MinDistance; //int max = GameConstants.MaxDistance; Vector3 tempCenter; //place ship wrecks foreach (ShipWreck shipWreck in shipWrecks) { shipWreck.Position = GenerateSeaBedRandomPosition(minX, maxX, minZ, maxZ, random, shipWrecks, staticObjects); //ship wreck should not be floating shipWreck.Position.Y = heightMapInfo.GetHeight(shipWreck.Position); tempCenter = shipWreck.BoundingSphere.Center; tempCenter.X = shipWreck.Position.X; tempCenter.Y = GameConstants.MainGameFloatHeight; tempCenter.Z = shipWreck.Position.Z; shipWreck.BoundingSphere = new BoundingSphere(tempCenter, shipWreck.BoundingSphere.Radius); //shipWreck.CalculateBoundingBox(1.0f, shipWreck.orientation); //ModifyBoundingBox(ref shipWreck.boundingBox, GameConstants.MainGameFloatHeight); } }
protected override void LoadContent() { terrain = game.Content.Load<Model>("terrain"); terrainTexture = game.Content.Load<Texture2D>("rocks"); decalTexture = game.Content.Load<Texture2D>("explosion_decal"); LoadTerrainEffects(); foreach (ModelMesh mesh in terrain.Meshes) { foreach (ModelMeshPart meshPart in mesh.MeshParts) { // Set the terrain texture // TODO: This part will have to go in the draw loop if we want the terrain to have // multiple textures. See: http://forums.create.msdn.com/forums/p/70607/432670.aspx // In fact, right now this next line of code is kind of stupid because it will result // the global terrainEffect to have the texture associated with the last mesh part // in the terrain mesh (because it keeps getting overwritten in the loop). Setting the // texture for the current mesh part is something that should be done when you // draw the terrain, as described in above forum post. terrainEffect.Texture = ((BasicEffect)meshPart.Effect).Texture; terrainEffect.TextureEnabled = true; meshPart.Effect = terrainEffect.Clone(); } } // The terrain processor attached a HeightMapInfo to the terrain model's // Tag. We'll save that to a member variable now, and use it to // calculate the terrain's heights later. heightMapInfo = terrain.Tag as HeightMapInfo; if (heightMapInfo == null) { string message = "The terrain model did not have a HeightMapInfo " + "object attached. Are you sure you are using the " + "TerrainProcessor?"; throw new InvalidOperationException(message); } sky = game.Content.Load<Sky>("sky"); }
public ChaseCamera(HeightMapInfo heightmap) { this.heightMap = heightmap; }
public void HandleInput(GamePadState currentGamePadState, KeyboardState currentKeyboardState, HeightMapInfo heightMapInfo) { if ( inputHelper.IsKeyJustPressed(Keys.C)) { mode += 1; if((int)mode == DesiredPositionOffsetSetting.Length) mode = 0; DesiredPositionOffset = DesiredPositionOffsetSetting[(int)mode]; LookAtOffset = LookAtOffsetSetting[(int)mode]; } if (currentKeyboardState.IsKeyDown(Keys.Add)) { DesiredPositionOffset *= 0.9f; } if (currentKeyboardState.IsKeyDown(Keys.Subtract)) { DesiredPositionOffset /= 0.9f; } }
// Sets up terrain, texture, ... private float[,] CreateTerrain(Texture2D heightMap) { float minimumHeight = 0; float maximumHeight = 255; int width = heightMap.Width; int height = heightMap.Height; boundingBox = new BoundingBox( new Vector3(-width / 2, maximumHeight - minimumHeight, -height / 2), new Vector3(width / 2, maximumHeight - minimumHeight, height / 2)); Color[] heightMapColors = new Color[width * height]; heightMap.GetData<Color>(heightMapColors); // Setup height data from heightmap float[,] heightData = new float[width, height]; for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { heightData[x, y] = heightMapColors[x + y * width].R; if (heightData[x, y] < minimumHeight) minimumHeight = heightData[x, y]; if (heightData[x, y] > maximumHeight) maximumHeight = heightData[x, y]; } } for (int x = 0; x < width; ++x) for (int y = 0; y < height; ++y) heightData[x, y] = (heightData[x, y] - minimumHeight) / (maximumHeight - minimumHeight) * 30; // Setup Physics heightMapInfo = new HeightMapInfo(heightData, 1); if (heightMapObject != null) { heightMapObject.DisableComponent(); heightMapObject = null; } heightMapObject = new HeightMapObject( heightMapInfo, new Vector2(heightMapInfo.Width / 2, -heightMapInfo.Height / 2 + heightMapInfo.Height)); return heightData; }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> public override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(device); spriteFont = content.Load<SpriteFont>("Arial"); camera = new ChaseCamera(heightMap); // Set the camera offsets camera.DesiredPositionOffset = new Vector3(0.0f, 100.0f, 200.0f); camera.LookAtOffset = new Vector3(0f, 15.0f, 30.0f); ball = new Ball(this, device, "Models\\balltest"); ball.scale = Vector3.One * 15f; camera.NearPlaneDistance = 10.0f; camera.FarPlaneDistance = 100000.0f; camera.AspectRatio = (float)device.Viewport.Width / device.Viewport.Height; camera.ChasePosition = ball.position; camera.ChaseDirection = ball.Direction; camera.Up = ball.Up; camera.Reset(); ballModel = content.Load<Model>("Models\\balltest"); pitModel = content.Load<Model>("Models\\ground"); boxModel = content.Load<Model>("Models\\cube"); arrowModel = content.Load<Model>("Models\\arrow"); exitModel = content.Load<Model>("Models\\exit2"); //exitModelText = content.Load<Model>("Models\\exitSign"); ballTextureBeach = content.Load<Texture2D>("Textures\\beach"); ballTextureMetal = content.Load<Texture2D>("Textures\\metal"); ballTextureAir = content.Load<Texture2D>("Textures\\air"); coinTexture = content.Load<Texture2D>("Textures\\coin"); teleporterTexture = content.Load<Texture2D>("Textures\\teleporter"); terrainModel = content.Load<Model>(terrain); rockTexture = content.Load<Texture2D>(terrainTexture); pitTextureLava = content.Load<Texture2D>("Textures\\lava"); pitTextureIce = content.Load<Texture2D>("Textures\\3"); scoreboardTexture = content.Load<Texture2D>("Textures\\highscores"); heightMap = terrainModel.Tag as HeightMapInfo; if (heightMap == null) { string message = "The terrain model did not have a HeightMapInfo"; throw new InvalidOperationException(message); } Sound.playSoundLoop(background, content); effect = content.Load<Effect>("Lighting/Effects"); sky = content.Load<Sky>("Textures\\sky"); /*Initialize properties for each ball*/ beachBallProperties = new BallProperties(ballTextureBeach, 1.0f, 0.5f, 900f, 1f, new Vector3(0.97f, 1f, 0.97f), new Vector3(1f, 1f, 1f), "Sound\\jump", "Sound\\jump", "Sound\\changeBall"); metalBallProperties = new BallProperties(ballTextureMetal, 3.0f, 0.15f, 750f, 3f, new Vector3(0.95f, 1f, 0.95f), new Vector3(1f, 1f, 1f), "Sound\\jump", "Sound\\jump", "Sound\\changeBall"); airBallProperties = new BallProperties(ballTextureAir, 1f, 0.05f, 1200f, 0.8f, new Vector3(0.99f, 0.99f, 0.99f), new Vector3(0.99f, 0.99f, 0.99f), "Sound\\jump", "Sound\\jump", "Sound\\changeBall"); currentBallProperties = beachBallProperties; List<Texture2D> textures = new List<Texture2D>(); textures.Add(Content.Load<Texture2D>("Textures\\circle")); textures.Add(Content.Load<Texture2D>("Textures\\star")); textures.Add(Content.Load<Texture2D>("Textures\\diamond")); particleEngine = new ParticleEngine(textures, new Vector2(100, 40)); //ExitPosition = new Vector3(1405.1f, .90952f, -2367.78f); ExitPosition = new Vector3(2000, 0f, 2000); ExitPosition.Y = getHeight(ExitPosition) + 50f; ExitBox = new BoundingBox(ExitPosition - new Vector3(50, 50, 50), ExitPosition + new Vector3(50, 50, 50)); for (int x = 0; x < 50; x++) { Vector3 Pos = new Vector3(RandomNumber(-2000, 2000), 0, RandomNumber(-2000, 2000)); //Vector3 Pos = new Vector3(0, 0, 0); Vector3 Normal; float Height; heightMap.GetHeightAndNormal(Pos, out Height, out Normal); Pos.Y = Height + 20; //System.Diagnostics.Debug.WriteLine(Pos); coinList.Add(new Coin(Pos, content)); } for (int x = 0; x < 20; x++) { Vector3 Pos = new Vector3(RandomNumber(-2500, 3000), 0, RandomNumber(-2500, 3000)); Vector3 Normal = new Vector3(); float Height = 10; heightMap.GetHeightAndNormal(Pos, out Height, out Normal); Pos.Y = Height + 50; //System.Diagnostics.Debug.WriteLine(Pos); teleporterList.Add(new teleporter(Pos, content)); } }
private void loadLevel() { string levelName = "level_"; levelName += (String) Convert.ToString(currentLevel + 1); p1Position = levelValues[currentLevel].initialPosition; p2Position = levelValues[currentLevel].initialPosition; p1Facing = 0; p2Facing = 0; p1Velocity = Vector3.Zero; p2Velocity = Vector3.Zero; flagPosition = Vector3.Zero; flagPosition.X = levelValues[currentLevel].xMax; flagPosition.Z = levelValues[currentLevel].yMax; terrain = Content.Load<Model>(levelName); // The terrain processor attached a HeightMapInfo to the terrain model's // Tag. We'll save that to a member variable now, and use it to // calculate the terrain's heights later. heightMapInfo = terrain.Tag as HeightMapInfo; if (heightMapInfo == null) { string message = "The terrain model did not have a HeightMapInfo " + "object attached. Are you sure you are using the " + "TerrainProcessor?"; throw new InvalidOperationException(message); } }
//PUBLIC METHODS /// <summary> /// Loads the specified heightmap from the a file. /// </summary> /// <param name="filename">filename to load</param> /// <param name="info">Heightmap info</param> /// <param name="heightmap">out heightmap</param> /// <returns>True/False heightmap can be loaded</returns> public static bool LoadFromFile(string filename, HeightMapInfo info, out HeightMap heightmap) { bool result = false; FileStream filestream = null; try { //OPEN THE FILESTREAM filestream = new FileStream(filename, FileMode.Open, FileAccess.Read); BinaryReader reader = new BinaryReader(filestream); //GENERATE NEW HEIGHTMAP HeightMap hmap = new HeightMap(); hmap.info = info; //GENERATE MAX X, Y VALUES int MaxX = hmap.info.size; int MaxY = hmap.info.size; //GENERATE X/Y ARRAY FOR hmap.HeightData = new float[MaxX, MaxY]; //READ ALL Z COORDS float size = (hmap.info.size / 2); for (int y = 0; y < MaxY; y++) { for (int x = 0; x < MaxX; x++) { hmap.HeightData[x, y] = (float)(((float)reader.ReadUInt16() - 32768) / 32768) * size; } } //CLOSE DOWN RESOURCES reader.Close(); filestream.Close(); heightmap = hmap; result = true; } catch (IOException) { //A IO-EXCEPTION OCCURED Trace.TraceError("Cannot load heightmap from file: {0}", filename); heightmap = null; result = false; } catch (OutOfMemoryException) { //WE RUN OUT OF MEMORY WHILE LOADING A MAP, THIS CAN BE THE RESULT OF CORRUPT MEMORY Trace.TraceError("Ran out of memory when attempting to load: {0}", filename); heightmap = null; result = false; } finally { //CLOSE DOWN RESOURCES if (filestream != null) { filestream.Close(); } } return(result); }
/// <summary> /// This function is called when the game is Updating in response to user input. /// It'll move the tank around the heightmap, and update all of the tank's /// necessary state. /// </summary> public void HandleInput(GamePadState currentGamePadState, KeyboardState currentKeyboardState, MouseState currentMouseState, HeightMapInfo heightMapInfo, GameTime gameTime) { //Recalculates turretDirection based on current mouse position if (currentPlayerState == PlayerState.Aim) { TurretDiff = new Vector3(currentMouseState.X, currentMouseState.Y, 0) - OriginalMousePos; TurretDiff = new Vector3(TurretDiff.X, -TurretDiff.Y, TurretDiff.Z); TurretDirection += TurretDiff; OriginalMousePos = new Vector3(currentMouseState.X, currentMouseState.Y, 0); if (TurretDirection.X > TurretRightBound) TurretDirection = new Vector3(TurretRightBound, TurretDirection.Y, TurretDirection.Z); else if (TurretDirection.X < TurretLeftBound) TurretDirection = new Vector3(TurretLeftBound, TurretDirection.Y, TurretDirection.Z); if (TurretDirection.Y > TurretUpBound) TurretDirection = new Vector3(TurretDirection.X, TurretUpBound, TurretDirection.Z); else if (TurretDirection.Y < TurretDownBound) TurretDirection = new Vector3(TurretDirection.X, TurretDownBound, TurretDirection.Z); } // First, we want to check to see if the tank should turn. turnAmount will // be an accumulation of all the different possible inputs. float turnAmount = -currentGamePadState.ThumbSticks.Left.X; if (currentKeyboardState.IsKeyDown(Keys.A) || currentGamePadState.DPad.Left == ButtonState.Pressed) { turnAmount += 5; } if (currentKeyboardState.IsKeyDown(Keys.D) || currentGamePadState.DPad.Right == ButtonState.Pressed) { turnAmount -= 5; } // clamp the turn amount between -1 and 1, and then use the finished // value to turn the tank. turnAmount = MathHelper.Clamp(turnAmount, -1, 1); if (game.currentTank.moves < moveLimit) facingDirection += turnAmount * TankTurnSpeed; bool canMove = !TankCollision(); // Next, we want to move the tank forward or back. to do this, // we'll create a Vector3 and modify use the user's input to modify the Z // component, which corresponds to the forward direction. Vector3 movement = Vector3.Zero; movement.Z = -currentGamePadState.ThumbSticks.Left.Y; if ((currentKeyboardState.IsKeyDown(Keys.W) || currentGamePadState.DPad.Up == ButtonState.Pressed)) { if (!canMove) { movement.Z = -4; } else { movement.Z = 1; game.currentTank.moves++; } } if ((currentKeyboardState.IsKeyDown(Keys.S) || currentGamePadState.DPad.Down == ButtonState.Pressed)) { if (!canMove) { movement.Z = 4; } else { movement.Z = -1; game.currentTank.moves++; } } // Next, we'll create a rotation matrix from the direction the tank is // facing, and use it to transform the vector. orientation = Matrix.CreateRotationY(FacingDirection); Vector3 velocity = Vector3.Transform(movement, orientation); velocity *= TankVelocity; if (game.currentTank.moves > moveLimit) velocity = Vector3.Zero; // Now we know how much the user wants to move. We'll construct a temporary // vector, newPosition, which will represent where the user wants to go. If // that value is on the heightmap, we'll allow the move. Vector3 newPosition = Position + velocity; if (heightMapInfo.IsOnHeightmap(newPosition)) { // Now that we know we're on the heightmap, we need to know the correct // height and normal at this position. Vector3 normal; heightMapInfo.GetHeightAndNormal(newPosition, out newPosition.Y, out normal); // As discussed in the doc, we'll use the normal of the heightmap // and our desired forward direction to recalculate our orientation // matrix. It's important to normalize, as well. orientation.Up = normal; orientation.Right = Vector3.Cross(orientation.Forward, orientation.Up); orientation.Right = Vector3.Normalize(orientation.Right); orientation.Forward = Vector3.Cross(orientation.Up, orientation.Right); orientation.Forward = Vector3.Normalize(orientation.Forward); // Now we need to roll the tank's wheels "forward." to do this, we'll // calculate how far they have rolled, and from there calculate how much // they must have rotated. float distanceMoved = Vector3.Distance(Position, newPosition); float theta = distanceMoved / TankWheelRadius; int rollDirection = movement.Z > 0 ? 1 : -1; wheelRollMatrix *= Matrix.CreateRotationX(theta * rollDirection); // once we've finished all computations, we can set our position to the // new position that we calculated. position = newPosition; } movingInstance.Volume = 0.20f; movingInstance.Play(); }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> public override void LoadContent() { graphics = (GraphicsDeviceManager) ScreenManager.Game.Services.GetService(typeof (IGraphicsDeviceManager)); //graphics.ToggleFullScreen(); // Construct our particle system components. explosionParticles = new ExplosionParticleSystem(ScreenManager.Game, ScreenManager.Game.Content); explosionSmokeParticles = new ExplosionSmokeParticleSystem(ScreenManager.Game, ScreenManager.Game.Content); projectileTrailParticles = new ProjectileTrailParticleSystem(ScreenManager.Game, ScreenManager.Game.Content); smokePlumeParticles = new SmokePlumeParticleSystem(ScreenManager.Game, ScreenManager.Game.Content); fireParticles = new FireParticleSystem(ScreenManager.Game, ScreenManager.Game.Content); // Set the draw order so the explosions and fire // will appear over the top of the smoke. smokePlumeParticles.DrawOrder = 100; explosionSmokeParticles.DrawOrder = 200; projectileTrailParticles.DrawOrder = 300; explosionParticles.DrawOrder = 400; fireParticles.DrawOrder = 500; // Load terrain terrain = ScreenManager.Game.Content.Load<Model>("terrain/terrain3"); // The terrain processor attached a HeightMapInfo to the terrain model's // Tag. We'll save that to a member variable now, and use it to // calculate the terrain's heights later. heightMapInfo = terrain.Tag as HeightMapInfo; if (heightMapInfo == null) { const string message = "The terrain model did not have a HeightMapInfo " + "object attached. Are you sure you are using the " + "TerrainProcessor?"; throw new InvalidOperationException(message); } // Load entities playerOne = new Player(this, "models/rio/rio_1", playerOneName, 1, true) {Position = new Vector3(400, 0, -400)}; ai = new Player(this, "models/rio/rio_2", playerTwoName, 2, true) {Position = new Vector3(200, 0, 200)}; ai.RandomMovementMinimalInterval = 0.01f; ai.RandomMovementMaximalnInterval = 0.03f; ai.RandomMovementRotationProbability = 0.3f; ai.MovesRandomly = true; surface = new Entity(this, "models/surface/surface", false, true); surface.Alpha = 0.6f; surface.MoveInTime = true; //surface.MaxMovementSpeed = 1.8f; surface.MovementSpeed = 0.0002f; surface.Friction = 0.00001f; surface.RotationX = MathHelper.ToRadians(180f); surface.Position = new Vector3(0, 500, 0); surface.IsBoundToHeightMap = false; Entites.Add(surface); Entites.Add(PlayerOne); Entites.Add(ai); CollideableEntites.Add(PlayerOne); CollideableEntites.Add(ai); AddMultipleInstancesOfEntity("models/egg/egg", 2, true, false, true); //AddMultipleInstancesOfEntity("models/grass/grassBig1", 30, false, true); //AddMultipleInstancesOfEntity("models/grass/grassBig2", 30, false, true); //AddMultipleInstancesOfEntity("models/grass/grassBig3", 30, false, true); //AddMultipleInstancesOfEntity("models/grass/grassBig4", 30, false, true); //AddMultipleInstancesOfEntity("models/grass/grassSmall1", 50, false, true); //AddMultipleInstancesOfEntity("models/grass/grassSmall2", 50, false, true); //AddMultipleInstancesOfEntity("models/grass/grassSmall3", 50, false, true); //AddMultipleInstancesOfEntity("models/grass/grassSmall4", 50, false, true); AddMultipleInstancesOfEntity("models/grassBunch/grassBunchSmall1", 80, false, true); AddMultipleInstancesOfEntity("models/grassBunch/grassBunchSmall2", 80, false, true); AddMultipleInstancesOfEntity("models/grassBunch/grassBunchSmall3", 80, false, true); AddMultipleInstancesOfEntity("models/grassBunch/grassBunchBig1", 60, false, true); AddMultipleInstancesOfEntity("models/grassBunch/grassBunchBig2", 60, false, true); AddMultipleInstancesOfEntity("models/grassBunch/grassBunchBig3", 60, false, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassBigBlue", 60, true, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassBigGreen", 60, true, true); //AddMultipleInstancesOfEntity("models/seaGrass/seaGrassBigPink", 60, true, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassBigRed", 60, true, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassBigViolet", 60, true, true); //AddMultipleInstancesOfEntity("models/seaGrass/seaGrassBigYellow", 60, true, true); AddMultipleInstancesOfEntity("models/seaGrassCylinder/seaGrassCylinderDorangev1", 30, true, true, false, 15); AddMultipleInstancesOfEntity("models/seaGrassCylinder/seaGrassCylinderDorangev2", 30, true, true, false, 15); AddMultipleInstancesOfEntity("models/seaGrassCylinder/seaGrassCylinderDorangev3", 30, true, true, false, 15); AddMultipleInstancesOfEntity("models/seaGrassCylinder/seaGrassCylinderOrangev1", 30, true, true, false, 15); AddMultipleInstancesOfEntity("models/seaGrassCylinder/seaGrassCylinderOrangev2", 30, true, true, false, 15); AddMultipleInstancesOfEntity("models/seaGrassCylinder/seaGrassCylinderOrangev3", 30, true, true, false, 15); AddMultipleInstancesOfEntity("models/seaGrassCylinder/seaGrassCylinderRedv1", 30, true, true, false, 15); AddMultipleInstancesOfEntity("models/seaGrassCylinder/seaGrassCylinderRedv2", 30, true, true, false, 15); AddMultipleInstancesOfEntity("models/seaGrassCylinder/seaGrassCylinderRedv3", 30, true, true, false, 15); AddMultipleInstancesOfEntity("models/seaGrassCylinder/seaGrassCylinder2Pink", 30, false, true, true, 15); AddMultipleInstancesOfEntity("models/seaGrassCylinder/seaGrassCylinder2Red", 30, false, true, true, 15); AddMultipleInstancesOfEntity("models/seaGrassCylinder/seaGrassCylinder2Violet", 30, false, true, true, 15); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassMiddleBlue", 65, true, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassMiddleGreen", 65, true, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassMiddleRed", 65, true, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassMiddleViolet", 65, true, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassMiddleYellow", 65, true, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassSmallBlue", 40, true, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassSmallGreen", 40, true, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassSmallRed", 40, true, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassSmallViolet", 40, true, true); AddMultipleInstancesOfEntity("models/seaGrass/seaGrassSmallYellow", 40, true, true); AddMultipleInstancesOfEntity("models/star/seaStarSlim", 85, true, true, false, 15, true); AddMultipleInstancesOfEntity("models/shell/shellOpen", 25, true, true); AddMultipleInstancesOfEntity("models/shell/shellHalfClose", 25, true, true); AddMultipleInstancesOfEntity("models/shell/shellClose", 25, true, true); AddMultipleInstancesOfEntity("models/mussel/musselOpen", 25, true, true); AddMultipleInstancesOfEntity("models/mussel/musselClose", 25, true, true); AddMultipleInstancesOfEntity("models/urchin/urchinBlack", 25, true, true); AddMultipleInstancesOfEntity("models/urchin/urchinRed", 25, true, true); AddMultipleInstancesOfEntity("models/urchin/urchinWithHairLongBlack", 25, true, true, true, 12, true); AddMultipleInstancesOfEntity("models/urchin/urchinWithHairLongRed", 25, true, true, true, 12, true); AddMultipleInstancesOfEntity("models/urchin/urchinWithHairShortBlack", 25, true, true, true, 12, true); AddMultipleInstancesOfEntity("models/urchin/urchinWithHairShortRed", 25, true, true, true, 12, true); AddMultipleInstancesOfEntity("models/stone/stone1_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone1_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone1_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone1_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone1_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone1_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone2_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone2_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone2_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone3_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone3_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone3_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone4_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone4_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone4_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone5_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone5_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone5_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone6_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone6_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone6_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone7_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone7_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone7_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone8_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone8_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone8_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone9_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone9_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone9_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone10_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone10_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone10_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone11_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone11_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone11_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone12_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone12_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone12_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone13_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone13_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone13_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone14_tex1", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone14_tex2", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stone14_tex3", 1, true, false, true, 70); AddMultipleInstancesOfEntity("models/stone/stoneGroup1_tex1", 1, true, false, true, 100); AddMultipleInstancesOfEntity("models/stone/stoneGroup1_tex2", 1, true, false, true, 100); AddMultipleInstancesOfEntity("models/stone/stoneGroup1_tex3", 1, true, false, true, 100); AddMultipleInstancesOfEntity("models/stone/stoneGroup2_tex1", 1, true, false, true, 100); AddMultipleInstancesOfEntity("models/stone/stoneGroup2_tex2", 1, true, false, true, 100); AddMultipleInstancesOfEntity("models/stone/stoneGroup2_tex3", 1, true, false, true, 100); AddMultipleInstancesOfEntity("models/stone/stoneGroup3_tex1", 1, true, false, true, 100); AddMultipleInstancesOfEntity("models/stone/stoneGroup3_tex2", 1, true, false, true, 100); AddMultipleInstancesOfEntity("models/stone/stoneGroup3_tex3", 1, true, false, true, 100); AddMultipleInstancesOfEntity("models/stone/stoneGroup4_tex1", 1, true, false, true, 100); AddMultipleInstancesOfEntity("models/stone/stoneGroup4_tex2", 1, true, false, true, 100); AddMultipleInstancesOfEntity("models/stone/stoneGroup4_tex3", 1, true, false, true, 100); /**/ // Components registration bloom = new BloomComponent(ScreenManager.Game); ScreenManager.Game.Components.Add(bloom); // Register the particle system components. ScreenManager.Game.Components.Add(explosionParticles); ScreenManager.Game.Components.Add(explosionSmokeParticles); ScreenManager.Game.Components.Add(projectileTrailParticles); ScreenManager.Game.Components.Add(smokePlumeParticles); ScreenManager.Game.Components.Add(fireParticles); // Enable background sound backgroundSound = ScreenManager.AudioManager.Play3DSound("sound/game_background", true, surface); spriteBatch = new SpriteBatch(graphics.GraphicsDevice); //ScreenManager.Game.Content.Load<SpriteFont>("fonts/hudFont"); //ScreenManager.Game.Content.Load<Texture2D>("images/hud"); background = ScreenManager.Game.Content.Load<Texture2D>("images/game/background"); foreach (Entity entity in Entites) entity.LoadContent(); ScreenManager.Game.ResetElapsedTime(); } public void setBloomPreset(String presetName) { BloomSettings preset = BloomSettings.PresetSettings[0]; foreach (var currentPreset in BloomSettings.PresetSettings) { if(currentPreset.Name.Equals(presetName)) { preset = currentPreset; break; } } bloom.Settings = preset; setBloomPresetCleaningTimeout(); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> public override void UnloadContent() { if (!backgroundSound.IsDisposed) backgroundSound.Stop(true); for (int i = ScreenManager.Game.Components.Count - 1; i > 1; i--) ScreenManager.Game.Components.RemoveAt(i); foreach (Entity entity in Entites) entity.UnloadContent(); foreach (Rocket entity in rockets) entity.UnloadContent(); } /// <summary> /// Allows the game to run logic. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { /*if(!_fpsCamera)*/ UpdateCamera(gameTime); // colission with player controls UpdateProjectiles(gameTime); presetCleanDelay -= gameTime.ElapsedGameTime; if (!bloom.Settings.Name.Equals(BloomSettings.PresetSettings[0].Name) && presetCleanDelay < TimeSpan.Zero) { setBloomPreset("Default"); } rocketGCDelay -= gameTime.ElapsedGameTime; if (rocketGCDelay < TimeSpan.Zero) { RocketGC(); rocketGCDelay += TimeSpan.FromSeconds(RocketGCInterval);; } foreach (Entity entity in Entites) entity.Update(gameTime, heightMapInfo); foreach (Rocket entity in rockets) entity.Update(gameTime, heightMapInfo); base.Update(gameTime, otherScreenHasFocus, false); }
protected virtual void OnCollision(Entity entity, GameTime gameTime, HeightMapInfo heightMapInfo) { //this._isBlocked = true; }
public static void placeTrash( ref List<Trash> trashes, ContentManager Content, Random random, List<ShipWreck> shipWrecks, List<StaticObject> staticObjects, int minX, int maxX, int minZ, int maxZ, GameMode gameMode, float floatHeight, HeightMapInfo heightMapInfo) { Vector3 tempCenter; int xVal, zVal, heightValue; //positionSign int numTries = 0; foreach (Trash trash in trashes) { //trash.Position = GenerateSurfaceRandomPosition(minX, maxX, minZ, maxZ, random, enemiesAmount, fishAmount, enemies, // fish, shipWrecks); do { xVal = random.Next(0, 2 * maxX) - maxX; zVal = random.Next(0, 2 * maxZ) - maxZ; //if (random.Next(100) % 2 == 0) // xVal *= -1; //if (random.Next(100) % 2 == 0) // zVal *= -1; heightValue = (int)heightMapInfo.GetHeight(new Vector3(xVal, 0, zVal)); //positionSign = random.Next(4); //switch (positionSign) //{ // case 0: // xVal *= -1; // break; // case 1: // zVal *= -1; // break; // case 2: // xVal *= -1; // zVal *= -1; // break; //} numTries++; } while (IsSeaBedPlaceOccupied(xVal, GameConstants.MainGameFloatHeight, zVal, 30, shipWrecks, staticObjects, trashes, null, null) && numTries < GameConstants.MaxNumTries); //no need to check with factories as this funciton is called only at the start of the game when factories are not present. trash.Position.X = xVal; trash.Position.Z = zVal; trash.Position.Y = trash.seaFloorHeight = heightValue; tempCenter = trash.BoundingSphere.Center; tempCenter.X = trash.Position.X; tempCenter.Y = floatHeight; tempCenter.Z = trash.Position.Z; trash.BoundingSphere = new BoundingSphere(tempCenter, trash.BoundingSphere.Radius); } }
/// <summary> /// This function is called when the game is Updating in response to user input. /// It'll move the tank around the heightmap, and update all of the tank's /// necessary state. /// </summary> public void HandleInput(GamePadState currentGamePadState, KeyboardState currentKeyboardState, HeightMapInfo heightMapInfo) { // First, we want to check to see if the tank should turn. turnAmount will // be an accumulation of all the different possible inputs. float turnAmount = -currentGamePadState.ThumbSticks.Left.X; if (currentKeyboardState.IsKeyDown(Keys.A) || //currentKeyboardState.IsKeyDown(Keys.Left) || currentGamePadState.DPad.Left == ButtonState.Pressed) { //turnAmount += 1; tank.movement.X = -1; } else if (currentKeyboardState.IsKeyDown(Keys.D) || //currentKeyboardState.IsKeyDown(Keys.Right) || currentGamePadState.DPad.Right == ButtonState.Pressed) { //turnAmount -= 1; tank.movement.X = +1; } else { tank.movement.X = 0; } // clamp the turn amount between -1 and 1, and then use the finished // value to turn the tank. turnAmount = MathHelper.Clamp(turnAmount, -1, 1); float facingDirection = tank.FacingDirection; facingDirection += turnAmount * TankTurnSpeed; tank.FacingDirection = facingDirection; // Next, we want to move the tank forward or back. to do this, // we'll create a Vector3 and modify use the user's input to modify the Z // component, which corresponds to the forward direction. Vector3 movement = Vector3.Zero; //movement.Z = -currentGamePadState.ThumbSticks.Left.Y; if (currentKeyboardState.IsKeyDown(Keys.W) || //currentKeyboardState.IsKeyDown(Keys.Up) || currentGamePadState.DPad.Up == ButtonState.Pressed) { tank.movement.Z = -1; } else if (currentKeyboardState.IsKeyDown(Keys.S) || //currentKeyboardState.IsKeyDown(Keys.Down) || currentGamePadState.DPad.Down == ButtonState.Pressed) { tank.movement.Z = 1; } else { tank.movement.Z = 0; } if (currentKeyboardState.IsKeyDown(Keys.LeftShift)) { if(boost != true) Velocity *= 1.5f; boost = true; } else { if (boost == true) { boost = false; Velocity /= 1.5f; } } /*if (currentKeyboardState.IsKeyDown(Keys.Space) && !shot) { if(AimEnemy != null) AimEnemy.ReceiveDamage(UnitTypes.BulletDamage[(int)UnitTypes.PlayerWeaponType.Canon], tank.ForwardVector); shot = true; } else if (currentKeyboardState.IsKeyUp(Keys.Space)) { shot = false; }*/ //tank.Move(facingDirection, movement, heightMapInfo,SteeringForce); MovePlayer(currentGamePadState, currentKeyboardState, heightMapInfo); }
/// <summary> /// This function is called when the game is Updating in response to user input. /// It'll move the tank around the heightmap, and update all of the tank's /// necessary state. /// </summary> public void Update(float elapsed, float turnAmount, Vector3 movement, HeightMapInfo heightMapInfo, Vector2 turretVector) { facingDirection += turnAmount * TankTurnSpeed * elapsed; // next, we'll create a rotation matrix from the direction the tank is // facing, and use it to transform the vector. Vector3 velocity = Vector3.Transform(movement, orientation); velocity *= TankVelocity; turretRotationValue = turretVector.X; cannonRotationValue = turretVector.Y; // Now we know how much the user wants to move. We'll construct a temporary // vector, newPosition, which will represent where the user wants to go. If // that value is on the heightmap, we'll allow the move. Vector3 newPosition = position + velocity * elapsed; if (heightMapInfo.IsOnHeightmap(newPosition)) { // now that we know we're on the heightmap, we need to know the correct // height and normal at this position. heightMapInfo.GetHeightAndNormal(newPosition, out newPosition.Y, out normal); // As discussed in the doc, we'll use the normal of the heightmap // and our desired forward direction to recalculate our orientation // matrix. It's important to normalize, as well. // now we need to roll the tank's wheels "forward." to do this, we'll // calculate how far they have rolled, and from there calculate how much // they must have rotated. float distanceMoved = Vector3.Distance(position, newPosition); float theta = distanceMoved / TankWheelRadius; int rollDirection = movement.Z > 0 ? 1 : -1; wheelRotationValue += theta * rollDirection; // once we've finished all computations, we can set our position to the // new position that we calculated. position = newPosition; } orientation = Matrix.CreateRotationY(FacingDirection); orientation.Up = normal; orientation.Right = Vector3.Cross(orientation.Forward, orientation.Up); orientation.Right = Vector3.Normalize(orientation.Right); orientation.Forward = Vector3.Cross(orientation.Up, orientation.Right); orientation.Forward = Vector3.Normalize(orientation.Forward); }
/// <summary> /// This function is called when the game is Updating in response to user input. /// It'll move the tank around the heightmap, and update all of the tank's /// necessary state. /// </summary> public void HandleInput(GamePadState currentGamePadState, KeyboardState currentKeyboardState, HeightMapInfo heightMapInfo) { // First, we want to check to see if the tank should turn. turnAmount will // be an accumulation of all the different possible inputs. float turnAmount = -currentGamePadState.ThumbSticks.Left.X; if (currentKeyboardState.IsKeyDown(Keys.A) || currentKeyboardState.IsKeyDown(Keys.Left) || currentGamePadState.DPad.Left == ButtonState.Pressed) { turnAmount += 1; } if (currentKeyboardState.IsKeyDown(Keys.D) || currentKeyboardState.IsKeyDown(Keys.Right) || currentGamePadState.DPad.Right == ButtonState.Pressed) { turnAmount -= 1; } // clamp the turn amount between -1 and 1, and then use the finished // value to turn the tank. turnAmount = MathHelper.Clamp(turnAmount, -1, 1); facingDirection += turnAmount * TankTurnSpeed; // Next, we want to move the tank forward or back. to do this, // we'll create a Vector3 and modify use the user's input to modify the Z // component, which corresponds to the forward direction. Vector3 movement = Vector3.Zero; movement.Z = -currentGamePadState.ThumbSticks.Left.Y; if (currentKeyboardState.IsKeyDown(Keys.W) || currentKeyboardState.IsKeyDown(Keys.Up) || currentGamePadState.DPad.Up == ButtonState.Pressed) { movement.Z = -1; } if (currentKeyboardState.IsKeyDown(Keys.S) || currentKeyboardState.IsKeyDown(Keys.Down) || currentGamePadState.DPad.Down == ButtonState.Pressed) { movement.Z = 1; } // next, we'll create a rotation matrix from the direction the tank is // facing, and use it to transform the vector. orientation = Matrix.CreateRotationY(FacingDirection); Vector3 velocity = Vector3.Transform(movement, orientation); velocity *= TankVelocity; // Now we know how much the user wants to move. We'll construct a temporary // vector, newPosition, which will represent where the user wants to go. If // that value is on the heightmap, we'll allow the move. Vector3 newPosition = Position + velocity; if (heightMapInfo.IsOnHeightmap(newPosition)) { // now that we know we're on the heightmap, we need to know the correct // height and normal at this position. Vector3 normal; heightMapInfo.GetHeightAndNormal(newPosition, out newPosition.Y, out normal); // As discussed in the doc, we'll use the normal of the heightmap // and our desired forward direction to recalculate our orientation // matrix. It's important to normalize, as well. orientation.Up = normal; orientation.Right = Vector3.Cross(orientation.Forward, orientation.Up); orientation.Right = Vector3.Normalize(orientation.Right); orientation.Forward = Vector3.Cross(orientation.Up, orientation.Right); orientation.Forward = Vector3.Normalize(orientation.Forward); // now we need to roll the tank's wheels "forward." to do this, we'll // calculate how far they have rolled, and from there calculate how much // they must have rotated. float distanceMoved = Vector3.Distance(Position, newPosition); float theta = distanceMoved / TankWheelRadius; int rollDirection = movement.Z > 0 ? 1 : -1; wheelRollMatrix *= Matrix.CreateRotationX(theta * rollDirection); // once we've finished all computations, we can set our position to the // new position that we calculated. position = newPosition; } }
public void FixGravity(HeightMapInfo heightMapInfo) { Vector3 newPosition = Position; if (heightMapInfo.IsOnHeightmap(newPosition)) { // now that we know we're on the heightmap, we need to know the correct // height and normal at this position. Vector3 normal; heightMapInfo.GetHeightAndNormal(newPosition, out newPosition.Y, out normal); // As discussed in the doc, we'll use the normal of the heightmap // and our desired forward direction to recalculate our orientation // matrix. It's important to normalize, as well. orientation.Up = normal; orientation.Right = Vector3.Cross(orientation.Forward, orientation.Up); orientation.Right = Vector3.Normalize(orientation.Right); orientation.Forward = Vector3.Cross(orientation.Up, orientation.Right); orientation.Forward = Vector3.Normalize(orientation.Forward); // Once we've finished all computations, we can set our position to the // new position that we calculated. position = newPosition; } }
public HeightMapObject(HeightMapInfo heightMapInfo, Vector2 shift) : base() { Setup(heightMapInfo, shift); }
public HeightMapObject(HeightMapInfo heightMapInfo, Vector2 shift, GameScreen parent) : base(parent) { Setup(heightMapInfo, shift); }
protected void MoveBack(GameTime gameTime, HeightMapInfo heightMapInfo) { Stop(gameTime); Decellerate(gameTime); ComputeSpeed(gameTime); AdjustToHeightMap(gameTime, heightMapInfo); Stop(gameTime); UpdateBoundingSphere(); }