public void HandleCollisions(Layer layer) { foreach (Tile tile in layer.Tiles) { if (BBox.Intersects(tile.BBox)) { Vector2 depth = RectangleExtensions.GetIntersectionDepth(BBox, tile.BBox); Position.X += depth.X; Velocity.X = -Velocity.X; } } }
/// <summary> /// Handle all the collisons for the player /// </summary> /// <param name="layer">The current layer the player is on</param> private void HandleCollisions(Layer layer) { bool onTile = false ; foreach(Tile tile in layer.Tiles) { if (BBox.Intersects(tile.BBox)) { Vector2 depth = RectangleExtensions.GetIntersectionDepth(BBox, tile.BBox); if (Underneath(tile)) { Position.Y += depth.Y; Velocity.Y = 0; } else if (OntopOf(tile)) { // We need to allow the player to glide across the top. Jumping = false; if (depth.Y < 0) { Position.Y += depth.Y; Velocity.Y = 0; onTile = true; } } else { Position.X += depth.X; Velocity.X = 0; } } } if (!onTile) { // Handle gravity if (Velocity.Y > Constants.MAX_FALL) { Velocity.Y = Constants.MAX_FALL; } else { Velocity.Y++; } } foreach (Enemy enemy in layer.Enemies) { if(BBox.Intersects(enemy.BBox)) { alive = false; } } if (layer.goal != null) { if (BBox.Intersects(layer.goal.BBox)) { Vector2 depth = RectangleExtensions.GetIntersectionDepth(BBox, layer.goal.BBox); Vector2 absDepth = new Vector2(Math.Abs(depth.X), Math.Abs(depth.Y)); if (absDepth.X > 50 && absDepth.Y > 50) { atGoal = true; } } } }
/// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public void Update(GameTime gameTime, Layer layer) { Position += Velocity; // Check bounding velocities if (Velocity.X > Constants.MAX_SPEED) { Velocity.X = Constants.MAX_SPEED; } if (Velocity.X < -Constants.MAX_SPEED) { Velocity.X = -Constants.MAX_SPEED; } if(Position.Y > 1000) { alive = false; } HandleCollisions(layer); base.Update(gameTime); }
/// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public void Update(GameTime gameTime, Layer layer) { HandleCollisions(layer); Position += Velocity; base.Update(gameTime); }