private bool CheckInteractables(GameObject source, ref BoundingBox boundingBox, Vector3 lookVector) { bool failMove = false; // Check against all the interactive objects foreach (GameObject target in CurrentLevel.Collidables) { IActivatable activatable = target as IActivatable; if (activatable == null) continue; if (!boundingBox.Intersects (TryGetOrStoreBox (target))) { if (source.Tracking.Contains (target.ID)) { activatable.Deactivate (source); source.Tracking.Remove (target.ID); } continue; } activatable.Activate (source, lookVector); source.Tracking.Add (target.ID); if (target.Dense) failMove = true; } return failMove; }
public void colisao() { Vector3 A = new Vector3(screen.player.positionPlayer.X+5, screen.player.positionPlayer.Y+10, 0); Vector3 B = new Vector3(screen.player.positionPlayer.X + 44, screen.player.positionPlayer.Y + screen.player.imgPlayer.Height - 13, 0); Vector3 C = new Vector3(posicao.X, posicao.Y, 0); Vector3 D = new Vector3(posicao.X + largura, posicao.Y + image.Height, 0); BoundingBox boxPlayer = new BoundingBox(A, B); BoundingBox boxEnemy = new BoundingBox(C, D); if (boxEnemy.Intersects(boxPlayer)) { screen.removeComponent(this); screen.addComponent(new Explosao(mygame, C + new Vector3(0, 10, 0), 1, screen)); screen.player.hp--; if (screen.player.hp < 0) { screen.addComponent(new Explosao(mygame, new Vector3(screen.player.positionPlayer.X, screen.player.positionPlayer.Y, 0), 2, screen)); screen.player.vida--; screen.player.hp = 5; } if(screen.player.vida < 0){ screen.removeComponent(screen.player); mygame.setScreen(new ScreenSplash(mygame)); } } }
public static void VisitTree(OctCell root, BoundingBox box, Action<OctCell> callback) { if (box.Intersects(root.Bounds)) { if (root.Leaf) callback(root); else foreach (var child in root.Children) VisitTree(child, box, callback); } }
public static void BuildTree(OctCell root, BoundingBox box, Action<OctCell> forLeaves, float leafSize) { if (box.Intersects(root.box)) { if ((root.box.Max.X - root.box.Min.X) <= leafSize) { if (root.contents == null) root.contents = new List<OctNode>(); forLeaves(root); } else { if (root.children == null) root.children = splitCell(root); foreach (var child in root.children) BuildTree(child, box, forLeaves, leafSize); } } }
public bool IsColliding(BoundingBox bbox, IEntity other) { //if (!Compare((int) KnownPosition.X, (int) other.KnownPosition.X, 5)) return false; //if (!Compare((int) KnownPosition.Z, (int) other.KnownPosition.Z, 5)) return false; if (!Compare((int)KnownPosition.X, (int)other.KnownPosition.X, 4)) { return(false); } if (!Compare((int)KnownPosition.Z, (int)other.KnownPosition.Z, 4)) { return(false); } if (!bbox.Intersects(other.GetBoundingBox())) { return(false); } return(true); }
public void GetEntries(Microsoft.Xna.Framework.BoundingBox boundingShape, IList <BroadPhaseEntry> overlaps) { //Compute the min and max of the bounding box. //Loop through the cells and select bounding boxes which overlap the x axis. Int2 min, max; Grid2DSortAndSweep.ComputeCell(ref boundingShape.Min, out min); Grid2DSortAndSweep.ComputeCell(ref boundingShape.Max, out max); for (int i = min.Y; i <= max.Y; i++) { for (int j = min.Z; j <= max.Z; j++) { //Grab the cell that we are currently in. Int2 cellIndex; cellIndex.Y = i; cellIndex.Z = j; GridCell2D cell; if (owner.cellSet.TryGetCell(ref cellIndex, out cell)) { //To fully accelerate this, the entries list would need to contain both min and max interval markers. //Since it only contains the sorted min intervals, we can't just start at a point in the middle of the list. //Consider some giant bounding box that spans the entire list. for (int k = 0; k < cell.entries.count && cell.entries.Elements[k].item.boundingBox.Min.X <= boundingShape.Max.X; k++) //TODO: Try additional x axis pruning? A bit of optimization potential due to overlap with AABB test. { bool intersects; var item = cell.entries.Elements[k].item; boundingShape.Intersects(ref item.boundingBox, out intersects); if (intersects && !overlaps.Contains(item)) { overlaps.Add(item); } } } } } }
public int[] Update(Vector2 characterPosition, Texture2D characterTexture) { int counter = 0; List<int> l = new List<int>(); int[] IDsToBeReturned; BoundingBox characterBox = new BoundingBox(new Vector3(characterPosition.X, characterPosition.Y, 0), new Vector3(characterPosition.X + characterTexture.Width, characterPosition.Y + characterTexture.Height, 0)); for (int i = 0; i < triggerArray.Length; i++) { if (characterBox.Intersects(triggerArray[i].BB)) { counter++; for (int j = 0; j < triggerArray[i].IDsToBeActivated.Length; j++) { int x = triggerArray[i].IDsToBeActivated[j]; l.Add(x); } } } IDsToBeReturned = l.ToArray(); return IDsToBeReturned; }
public PlaneIntersectionType Intersects(BoundingBox box) { return(box.Intersects(this)); }
/*Checks for objects within explosion range *(dictated by the closest colliding wall to the bombs original explosion range) */ private List<GameEntity> ExplosionCollision(Bomb b, BoundingBox bB, float explosionLength) { List<GameEntity> affectedByExplosion = new List<GameEntity>(); float temp; //does bomb hit player? if (bB.Intersects(m_Player.BoundingSphere)) { affectedByExplosion.Add(m_Player); } #region Blocks in explosion range for (int i = 0; i < m_Blocks.Count; i++) { if (bB.Intersects(m_Blocks[i].BoundingBox)) { temp = Vector3.Distance(b.Position, m_Blocks[i].Position); if (temp <= explosionLength) { affectedByExplosion.Add(m_Blocks[i]); } } } #endregion #region Agents in explosion range for (int i = 0; i < m_Agents.Count; i++) { if (bB.Intersects(m_Agents[i].BoundingSphere)) { temp = Vector3.Distance(b.Position, m_Agents[i].Position); if (temp <= explosionLength) { affectedByExplosion.Add(m_Agents[i]); } } } #endregion #region Bombs in explosion range for (int i = 0; i < m_Bombs.Count; i++) { if (bB.Intersects(m_Bombs[i].BoundingSphere)) { temp = Vector3.Distance(b.Position, m_Bombs[i].Position); if (temp <= explosionLength) { affectedByExplosion.Add(m_Bombs[i]); } } } #endregion return affectedByExplosion; }
/// <summary> /// Gets whether or not a specified <see cref="BoundingBox"/> intersects with this sphere. /// </summary> /// <param name="box">The box for testing.</param> /// <param name="result"><c>true</c> if <see cref="BoundingBox"/> intersects with this sphere; <c>false</c> otherwise. As an output parameter.</param> public void Intersects(ref BoundingBox box, out bool result) { box.Intersects(ref this, out result); }
/// <summary> /// Checks if object intersects with other /// </summary> /// <param name="obj">Displayobject to check intersection with</param> /// <returns>true, if objects intersects, false otherwise</returns> public virtual bool HitTestObject(DisplayObject obj) { throw new NotImplementedException("A HitTestObject is not implemented yet"); var bounds1 = GetBounds(); var bounds2 = obj.GetBounds(); // TODO: Coordinates should be all transformed to global! // Global first body var topLeft1_g = this.LocalToGlobal(new Vector2(bounds1.X, bounds1.Y)); var botRight1_g = this.LocalToGlobal(new Vector2(bounds1.Z, bounds1.W)); // Global second body var topLeft2_g = obj.LocalToGlobal(new Vector2(bounds2.X, bounds2.Y)); var botRight2_g = obj.LocalToGlobal(new Vector2(bounds2.Z, bounds2.W)); // Setup boundig boxes BoundingBox bb1 = new BoundingBox(new Vector3(topLeft1_g, 0), new Vector3(botRight1_g, 0)); BoundingBox bb2 = new BoundingBox(new Vector3(topLeft2_g, 0), new Vector3(botRight2_g, 0)); return bb1.Intersects(bb2); }
public bool IntersectRay(Microsoft.Xna.Framework.Ray r) { float?res = box.Intersects(r); return(res.HasValue); }
/// <summary> /// Check ball collisions /// </summary> void CheckBallCollisions(float moveFactorPerSecond) { // Check top, left and right screen borders float MinYPos = 0.0235f; if (ballPosition.Y < MinYPos) { ballSpeedVector.Y = -ballSpeedVector.Y; // Move ball back into screen space if (ballPosition.X < MinYPos) ballPosition.X = MinYPos; // Play hit sound soundBank.PlayCue("PongBallHit"); } // if float MinXPos = 0.018f; if (ballPosition.X < MinXPos || ballPosition.X > 1 - MinXPos) { ballSpeedVector.X = -ballSpeedVector.X; // Move ball back into screen space if (ballPosition.X < MinXPos) ballPosition.X = MinXPos; if (ballPosition.X > 1 - MinXPos) ballPosition.X = 1 - MinXPos; // Play hit sound soundBank.PlayCue("PongBallHit"); } // if // Check for collisions with the paddles // Construct bounding boxes to use the intersection helper method. Vector2 ballSize = new Vector2(24 / 1024.0f, 24 / 768.0f); BoundingBox ballBox = new BoundingBox( new Vector3(ballPosition.X - ballSize.X / 2, ballPosition.Y - ballSize.Y / 2, 0), new Vector3(ballPosition.X + ballSize.X / 2, ballPosition.Y + ballSize.Y / 2, 0)); Vector2 paddleSize = new Vector2( GamePaddleRect.Width / 1024.0f, GamePaddleRect.Height / 768.0f); BoundingBox paddleBox = new BoundingBox( new Vector3(paddlePosition - paddleSize.X / 2, 0.95f-paddleSize.Y * 0.7f, 0), new Vector3(paddlePosition + paddleSize.X / 2, 0.95f, 0)); // Ball hit paddle? if (ballBox.Intersects(paddleBox)) { // Bounce off in the direction vector from the paddle ballSpeedVector.X += (ballPosition.X - paddlePosition) / (MinXPos * 3); // Max to -1 and +1 if (ballSpeedVector.X < -1) ballSpeedVector.X = -1; if (ballSpeedVector.X > 1) ballSpeedVector.X = 1; // Bounce of the paddle ballSpeedVector.Y = -1;// -ballSpeedVector.Y; // Move away from the paddle ballPosition.Y -= moveFactorPerSecond * BallSpeedMultiplicator; // Normalize vector ballSpeedVector.Normalize(); // Play sound soundBank.PlayCue("PongBallHit"); } // if // Ball hits any block? for (int y = 0; y < NumOfRows; y++) for (int x = 0; x < NumOfColumns; x++) if (blocks[x, y]) { // Collision check if (ballBox.Intersects(blockBoxes[x, y])) { // Kill block blocks[x, y] = false; // Add score score++; // Update title Window.Title = "XnaBreakout - Level " + (level + 1) + " - Score " + score; // Play sound soundBank.PlayCue("BreakoutBlockKill"); // Bounce ball back, but first find out which side we hit. // Start with left/right borders. if (Math.Abs(blockBoxes[x, y].Max.X - ballBox.Min.X) < moveFactorPerSecond) { ballSpeedVector.X = Math.Abs(ballSpeedVector.X); // Also move back a little ballPosition.X += (ballSpeedVector.X < 0 ? -1 : 1) * moveFactorPerSecond; } // else else if (Math.Abs(blockBoxes[x, y].Min.X - ballBox.Max.X) < moveFactorPerSecond) { ballSpeedVector.X = -Math.Abs(ballSpeedVector.X); // Also move back a little ballPosition.X += (ballSpeedVector.X < 0 ? -1 : 1) * moveFactorPerSecond; } // else // Now check top/bottom borders else if (Math.Abs(blockBoxes[x, y].Max.Y - ballBox.Min.Y) < moveFactorPerSecond) { ballSpeedVector.Y = Math.Abs(ballSpeedVector.Y); // Also move back a little ballPosition.Y += (ballSpeedVector.Y < 0 ? -1 : 1) * moveFactorPerSecond; } // if else if (Math.Abs(blockBoxes[x, y].Min.Y - ballBox.Max.Y) < moveFactorPerSecond) { ballSpeedVector.Y = -Math.Abs(ballSpeedVector.Y); // Also move back a little ballPosition.Y += (ballSpeedVector.Y < 0 ? -1 : 1) * moveFactorPerSecond; } // else else ballSpeedVector *= -1; // Go outa here, only handle 1 block at a time break; } // if } // for for if }
// ----------------------- Feng ------------------------------------------------ // check if the rocket runs into a hazard private void CheckCollision(Hazard theHazard) { // wrap the hazard and car with BoundingBox BoundingBox aHazardBox = new BoundingBox(new Vector3(theHazard.Position.X, theHazard.Position.Y, 0), new Vector3(theHazard.Position.X + (mHazard.Width * .5f), theHazard.Position.Y + ((mHazard.Height) * .5f), 0)); BoundingBox aCarBox = new BoundingBox(new Vector3(mCarPosition.X, mCarPosition.Y, 0), new Vector3(mCarPosition.X + (mCar.Width * .8f), mCarPosition.Y + (mCar.Height * .8f), 0)); BoundingBox aCarBoxPerfect = new BoundingBox(new Vector3(mCarPosition.X, mCarPosition.Y, 0), new Vector3(mCarPosition.X + (mCar.Width * .8f), mCarPosition.Y + (mCar.Height * .8f) * 0.05f, 0)); BoundingBox aHazardBoxPerfect = new BoundingBox(new Vector3(theHazard.Position.X, theHazard.Position.Y + (mHazard.Height * .25f), 0), new Vector3(theHazard.Position.X + (mHazard.Width * .5f), theHazard.Position.Y + ((mHazard.Height) * .5f), 0)); if (aHazardBox.Intersects(aCarBox) == true) // collided { if (aHazardBoxPerfect.Intersects(aCarBoxPerfect) == true) { mScore += 2; mHazardsPerfect++; theHazard.sign = Hazard.Sign.Perfect; } else { mScore++; mHazardsGood++; theHazard.sign = Hazard.Sign.Good; } mHazardsCombo++; hitSE.Play(); theHazard.Visible = false; theHazard.SignDisplayTime = (double)mHazard.Height / mVelocityY; // show "Perfect" or "Good" in the game scene } }
protected override void Update(GameTime gameTime) { Vector3 velocity = cam.ProcessKeyboardInput(gameTime); BoundingBox soldierbox = new BoundingBox(new Vector3(soldier.Position.X - 0.3f, soldier.Position.Y, soldier.Position.Z - 0.2f), new Vector3(soldier.Position.X + 0.3f, soldier.Position.Y + 1.8f, soldier.Position.Z + 0.2f)); Collider c = new Collider(); if (c.isColliding(city.BuildingBounds, cam, new Vector3(3, 1, 3)) || c.isColliding(soldierbox, cam, new Vector3(3, 1, 3))) { velocity *= -3.0f; } foreach (Projectile bullet in weaponManager.GetModel(gunIndex).bullets) { if (!bullet.destroy) { BoundingBox bulletbox = new BoundingBox(new Vector3(bullet.Position.X + 0.015f, bullet.Position.Y + 0.015f, bullet.Position.Z - 0.055f), new Vector3(bullet.Position.X - 0.015f, bullet.Position.Y - 0.015f, bullet.Position.Z + 0.07f)); if (soldierbox.Intersects(bulletbox)) { bullet.destroy = true; soldier.Shot(20.0f); } else { foreach (BoundingBox building in city.BuildingBounds) { if (building.Contains(bulletbox) == ContainmentType.Contains) { bullet.destroy = true; } } } } } cam.Update(gameTime, velocity); weaponManager.GetModel(gunIndex).Update(gameTime); base.Update(gameTime); }
void detectBallBrickCollision() { Vector3 ballMin = new Vector3(ballPos.X, ballPos.Y, 0); Vector3 ballMax = new Vector3(ballPos.X + ball.Width, ballPos.Y + ball.Height, 0); BoundingBox bb1 = new BoundingBox(ballMin, ballMax); Vector2 nearestPnt = ballPos; Vector3 brickMin, brickMax; for (int i = 0; i < blocksPos.Length; i++) { if (blocksPos[i] != Vector2.Zero) { brickMin = new Vector3(blocksPos[i].X, blocksPos[i].Y, 0); brickMax = new Vector3(blocksPos[i].X + block.Width, blocksPos[i].Y + block.Height, 0); if (bb1.Intersects(new BoundingBox(brickMin, brickMax))) { //what should we do? change x or y velocity? //checking to see if it's to left of brick if (ballPos.X < blocksPos[i].X && Math.Abs(blocksPos[i].Y - ballPos.Y) <= ball.Width / 2) { ballVel.X *= -1; ballPos.X = blocksPos[i].X - ball.Width; } //check to see if it's too the right else if (ballPos.X + ball.Width > blocksPos[i].X + block.Width && Math.Abs(blocksPos[i].Y - ballPos.Y) <= ball.Width / 2) { ballVel.X *= -1; ballPos.X = blocksPos[i].X + block.Width; } else { ballVel.Y *= -1; if (ballPos.Y < blocksPos[i].Y) { ballPos.Y = blocksPos[i].Y - ball.Height + 1; } else { ballPos.Y = blocksPos[i].Y + block.Height - 1; } } blocksPos[i] = Vector2.Zero; } } } }
/// <summary> /// Aktualisiert den Spieler (Bewegung, Interaktion) /// </summary> /// <param name="frameTime">Die aktuelle Zeit.</param> public void Update(GameTime frameTime) { #region Inputverarbeitung // Input verarbeiten Player.Angle += (float)frameTime.ElapsedGameTime.TotalSeconds * Head.X; Player.Tilt += (float)frameTime.ElapsedGameTime.TotalSeconds * Head.Y; Player.Tilt = Math.Min(1.5f, Math.Max(-1.5f, Player.Tilt)); #endregion #region Physik float lookX = (float)Math.Cos(Player.Angle); float lookY = -(float)Math.Sin(Player.Angle); var velocitydirection = new Vector3(lookX, lookY, 0) * Move.Y; float stafeX = (float)Math.Cos(Player.Angle + MathHelper.PiOver2); float stafeY = -(float)Math.Sin(Player.Angle + MathHelper.PiOver2); velocitydirection += new Vector3(stafeX, stafeY, 0) * Move.X; Player.Velocity += PhysicalUpdate(velocitydirection, frameTime.ElapsedGameTime, !Player.FlyMode, Player.FlyMode); #endregion #region Playerbewegung /Kollision Vector3 move = Player.Velocity * (float)frameTime.ElapsedGameTime.TotalSeconds; Player.OnGround = false; //Blocks finden die eine Kollision verursachen könnten int minx = (int)Math.Floor(Math.Min( Player.Position.BlockPosition.X - Player.Radius, Player.Position.BlockPosition.X - Player.Radius + move.X)); int maxx = (int)Math.Ceiling(Math.Max( Player.Position.BlockPosition.X + Player.Radius, Player.Position.BlockPosition.X + Player.Radius + move.X)); int miny = (int)Math.Floor(Math.Min( Player.Position.BlockPosition.Y - Player.Radius, Player.Position.BlockPosition.Y - Player.Radius + move.Y)); int maxy = (int)Math.Ceiling(Math.Max( Player.Position.BlockPosition.Y + Player.Radius, Player.Position.BlockPosition.Y + Player.Radius + move.Y)); int minz = (int)Math.Floor(Math.Min( Player.Position.BlockPosition.Z, Player.Position.BlockPosition.Z + move.Z)); int maxz = (int)Math.Ceiling(Math.Max( Player.Position.BlockPosition.Z + Player.Height, Player.Position.BlockPosition.Z + Player.Height + move.Z)); //Beteiligte Flächen des Spielers var playerplanes = CollisionPlane.GetPlayerCollisionPlanes(Player).ToList(); bool abort = false; for (int z = minz; z <= maxz && !abort; z++) { for (int y = miny; y <= maxy && !abort; y++) { for (int x = minx; x <= maxx && !abort; x++) { move = Player.Velocity * (float)frameTime.ElapsedGameTime.TotalSeconds; Index3 pos = new Index3(x, y, z); Index3 blockPos = pos + Player.Position.GlobalBlockIndex; ushort block = localChunkCache.GetBlock(blockPos); if (block == 0) continue; var blockplane = CollisionPlane.GetBlockCollisionPlanes(pos, Player.Velocity).ToList(); var planes = from pp in playerplanes from bp in blockplane where CollisionPlane.Intersect(bp, pp) let distance = CollisionPlane.GetDistance(bp, pp) where CollisionPlane.CheckDistance(distance, move) select new { BlockPlane = bp, PlayerPlane = pp, Distance = distance }; foreach (var plane in planes) { var subvelocity = (plane.Distance / (float)frameTime.ElapsedGameTime.TotalSeconds); var diff = Player.Velocity - subvelocity; float vx; float vy; float vz; if (plane.BlockPlane.normal.X != 0 && (Player.Velocity.X > 0 && diff.X >= 0 && subvelocity.X >= 0 || Player.Velocity.X < 0 && diff.X <= 0 && subvelocity.X <= 0)) vx = subvelocity.X; else vx = Player.Velocity.X; if (plane.BlockPlane.normal.Y != 0 && (Player.Velocity.Y > 0 && diff.Y >= 0 && subvelocity.Y >= 0 || Player.Velocity.Y < 0 && diff.Y <= 0 && subvelocity.Y <= 0)) vy = subvelocity.Y; else vy = Player.Velocity.Y; if (plane.BlockPlane.normal.Z != 0 && (Player.Velocity.Z > 0 && diff.Z >= 0 && subvelocity.Z >= 0 || Player.Velocity.Z < 0 && diff.Z <= 0 && subvelocity.Z <= 0)) vz = subvelocity.Z; else vz = Player.Velocity.Z; Player.Velocity = new Vector3(vx, vy, vz); if (vx == 0 && vy == 0 && vz == 0) { abort = true; break; } } } } } // TODO: Was ist für den Fall Gravitation = 0 oder im Scheitelpunkt des Sprungs? Player.OnGround = Player.Velocity.Z == 0f; Coordinate position = Player.Position + Player.Velocity * (float)frameTime.ElapsedGameTime.TotalSeconds; position.NormalizeChunkIndexXY(planet.Size); Player.Position = position; //Beam me up KeyboardState ks = Keyboard.GetState(); if (ks.IsKeyDown(Keys.P)) { Player.Position += new Vector3(0, 0, 10); } if (Player.Position.ChunkIndex != _oldIndex) { _oldIndex = Player.Position.ChunkIndex; ReadyState = false; localChunkCache.SetCenter(planet, new Index2(Player.Position.ChunkIndex), (success) => { ReadyState = success; }); } #endregion #region Block Interaction if (lastInteract.HasValue) { ushort lastBlock = localChunkCache.GetBlock(lastInteract.Value); localChunkCache.SetBlock(lastInteract.Value, 0); if (lastBlock != 0) { var blockDefinition = DefinitionManager.Instance.GetBlockDefinitionByIndex(lastBlock); var slot = Player.Inventory.Where(s => s.Definition == blockDefinition && s.Amount < blockDefinition.StackLimit).FirstOrDefault(); // Wenn noch kein Slot da ist oder der vorhandene voll, dann neuen Slot if (slot == null || slot.Amount >= blockDefinition.StackLimit) { slot = new InventorySlot() { Definition = blockDefinition, Amount = 0 }; Player.Inventory.Add(slot); } slot.Amount++; } lastInteract = null; } if (lastApply.HasValue) { if (ActiveTool != null) { Index3 add = new Index3(); switch (lastOrientation) { case OrientationFlags.SideWest: add = new Index3(-1, 0, 0); break; case OrientationFlags.SideEast: add = new Index3(1, 0, 0); break; case OrientationFlags.SideSouth: add = new Index3(0, -1, 0); break; case OrientationFlags.SideNorth: add = new Index3(0, 1, 0); break; case OrientationFlags.SideBottom: add = new Index3(0, 0, -1); break; case OrientationFlags.SideTop: add = new Index3(0, 0, 1); break; } if (ActiveTool.Definition is IBlockDefinition) { IBlockDefinition definition = ActiveTool.Definition as IBlockDefinition; Index3 idx = lastApply.Value + add; var boxes = definition.GetCollisionBoxes(localChunkCache, idx.X, idx.Y, idx.Z); float gap = 0.01f; var playerBox = new BoundingBox( new Vector3( Player.Position.GlobalBlockIndex.X + Player.Position.BlockPosition.X - Player.Radius + gap, Player.Position.GlobalBlockIndex.Y + Player.Position.BlockPosition.Y - Player.Radius + gap, Player.Position.GlobalBlockIndex.Z + Player.Position.BlockPosition.Z + gap), new Vector3( Player.Position.GlobalBlockIndex.X + Player.Position.BlockPosition.X + Player.Radius - gap, Player.Position.GlobalBlockIndex.Y + Player.Position.BlockPosition.Y + Player.Radius - gap, Player.Position.GlobalBlockIndex.Z + Player.Position.BlockPosition.Z + Player.Height - gap) ); // Nicht in sich selbst reinbauen bool intersects = false; foreach (var box in boxes) { var newBox = new BoundingBox(idx + box.Min, idx + box.Max); if (newBox.Intersects(playerBox)) intersects = true; } if (!intersects) { localChunkCache.SetBlock(idx, DefinitionManager.Instance.GetBlockDefinitionIndex(definition)); ActiveTool.Amount--; if (ActiveTool.Amount <= 0) { Player.Inventory.Remove(ActiveTool); ActiveTool = null; } } } // TODO: Fix Interaction ;) //ushort block = _manager.GetBlock(lastApply.Value); //IBlockDefinition blockDefinition = BlockDefinitionManager.GetForType(block); //IItemDefinition itemDefinition = ActiveTool.Definition; //blockDefinition.Hit(blockDefinition, itemDefinition.GetProperties(null)); //itemDefinition.Hit(null, blockDefinition.GetProperties(block)); } lastApply = null; } #endregion }
public void PerformAttack(Vector3 position, PlayerDirection facing, Move newMove, float increase) { bool enemyHit = false; bool shieldHit = false; string soundName = null; if (newMove.Sound_hit != String.Empty) soundName = newMove.Sound_hit; float damage = newMove.Damage + newMove.Damage * increase; float rockMeter = newMove.RockMeterIncrease; //bouding box const float DEPTH_CONST = 100; const float HEIGHT_CONST = 2; BoundingBox hitbox = new BoundingBox(); float front = newMove.FrontArea + newMove.FrontArea * increase; float back = newMove.BackArea + newMove.BackArea * increase; hitbox.Min.Y = position.Y - HEIGHT_CONST - HEIGHT_CONST * increase; hitbox.Max.Y = position.Y + HEIGHT_CONST + HEIGHT_CONST * increase; Vector3 force = Vector3.Zero; switch (facing) { case PlayerDirection.Right: hitbox.Min.X = position.X - back; hitbox.Max.X = position.X + front; hitbox.Min.Z = position.Z - DEPTH_CONST; hitbox.Max.Z = position.Z + DEPTH_CONST; force = Vector3.Right; break; case PlayerDirection.Left: hitbox.Min.X = position.X - front; hitbox.Max.X = position.X + back; hitbox.Min.Z = position.Z - DEPTH_CONST; hitbox.Max.Z = position.Z + DEPTH_CONST; force = Vector3.Right; break; case PlayerDirection.Forward: hitbox.Min.X = position.X - DEPTH_CONST; hitbox.Max.X = position.X + DEPTH_CONST; hitbox.Min.Z = position.Z - front; hitbox.Max.Z = position.Z + back; force = Vector3.Backward; break; case PlayerDirection.Backward: hitbox.Min.X = position.X - DEPTH_CONST; hitbox.Max.X = position.X + DEPTH_CONST; hitbox.Min.Z = position.Z - back; hitbox.Max.Z = position.Z + front; force = Vector3.Backward; break; } // todo: move to a better place. maybe a function in player agent called "SmashEffects" or something like that. maybe a class called "PlayerAttackEffects" and a static function called "Smash" in there if (newMove.Name == "Smash") { Vector3 difference = hitbox.Max - hitbox.Min; float length = difference.Z; float height = difference.Y; float width = difference.X; Vector3 center = new Vector3(hitbox.Max.X - width / 2.0f, hitbox.Max.Y - height / 2.0f, hitbox.Max.Z - length / 2.0f); Stage.ActiveStage.GetQB<Engine.Decals.DecalQB>().CreateDecal(new Ray(center, Vector3.Down), 10.0f, "Decals/crack", 10.0f, 20.0f, Decals.DecalLayers.CracksLayer); Stage.ActiveStage.GetQB<Particles.ParticleQB>().AddParticleEmitter(null, mainCharacter.PhysicsObject.Position + new Vector3(0.0f, -3.0f, 0.0f), true, -1f, 50, 75, 1.0f, 1.5f, 4, 5, new Vector2(1.0f), new Vector2(2.0f), new Vector3(1.0f, 0.0f, 1.0f), Vector3.Up, new Vector3(8.4f, 0.3f, 8.4f), "dust2"); Stage.ActiveStage.GetQB<AudioQB>().PlaySound("WeakAOE_16", 1.0f, 0.0f, 0.0f); Stage.ActiveStage.GetQB<AudioQB>().PlaySound("asphaltsmash_16", 0.7f, 0.0f, 0.0f); } Actor actor; foreach (GameLib.Engine.AI.AI ai in Stage.ActiveStage.GetQB<GameLib.Engine.AI.AIQB>().aliveEnemies) { actor = ai.actor; if (hitbox.Intersects(actor.PhysicsObject.CollisionInformation.BoundingBox)) { enemyHit = true; Vector3 actorPos = actor.PhysicsObject.Position; HealthAgent actorHealth = actor.GetAgent<HealthAgent>(); float startingHealth = actorHealth.Health; float remainingHealth = actorHealth.ModifyHealth(-damage, mainCharacter.PhysicsObject.Position, newMove.Disarming); if (remainingHealth < startingHealth) { if (newMove.Force != Vector2.Zero && remainingHealth > 0) { force *= (actorPos - position); force.Normalize(); force.X *= newMove.Force.X + newMove.Force.X * increase; force.X *= newMove.Force.X + newMove.Force.X * increase; float jumpVal = newMove.Force.Y + newMove.Force.Y * increase; if (actor.PhysicsObject.physicsType == PhysicsObject.PhysicsType.CylinderCharacter) { actor.PhysicsObject.CylinderCharController.Body.LinearVelocity = Vector3.Zero; if (jumpVal != 0) { actor.PhysicsObject.CylinderCharController.Jump(jumpVal / actor.PhysicsObject.CylinderCharController.Body.Mass); } if (force != Vector3.Zero) actor.PhysicsObject.CylinderCharController.Body.ApplyLinearImpulse(ref force); } } //we did damage so increase the multiplier playerRockMeter.PerformedAttack(rockMeter); //stun the enemy if (newMove.StunTime != 0.0f) ai.Stun(newMove.StunTime); if (ai.bloodOnDamage) { Vector3 bloodDir = actorPos - mainCharacter.PhysicsObject.Position; bloodDir.Normalize(); bloodDir *= 10; Stage.ActiveStage.GetQB<Particles.ParticleQB>().AddParticleEmitter(null, actor.PhysicsObject.Position, true, -1, 5, 10, .25f, .5f, 0, 0, Vector2.One, Vector2.One * 2.0f, Vector3.Zero, bloodDir, 2 * Vector3.One, "blood1"); Stage.ActiveStage.GetQB<Gameplay.BloodSplatterQB>().SplatBlood(); Stage.ActiveStage.GetQB<Decals.DecalQB>().CreateDecal(actorPos, new BoundingBox(new Vector3(-20.0f, -20.0f, -20.0f), new Vector3(20.0f, 20.0f, 20.0f)), "Decals/blood", 10.0f, 5.0f, Decals.DecalLayers.BloodLayer); //Stage.ActiveStage.GetQB<Decals.DecalQB>().CreateDecal(new Ray(actor.PhysicsObject.Position, Vector3.Down), 10.0f, "Decals/blood", 10.0f, 5.0f, Decals.DecalLayers.BloodLayer); } if (remainingHealth <= 0.0f) //killed the enemy { //playerRockMeter.IncreaseRockLevel(ai.rockLevelForKilling); int increaseRockMeter = playerRockMeter.IncreaseScoreDueToKill(ai.pointsForKilling); playerRockMeter.AddKill(); Vector3 screenPos = Stage.renderer.GraphicsDevice.Viewport.Project(actorPos, CameraQB.ProjectionMatrix, CameraQB.ViewMatrix, Matrix.Identity); Stage.ActiveStage.GetQB<ParticleQB>().AddFloatingText(new Vector2(screenPos.X, screenPos.Y + 10), -50 * Vector2.UnitY, 2.0f, increaseRockMeter.ToString(System.Globalization.CultureInfo.InvariantCulture)); } } else //you hit an enemy but dealt no damage { shieldHit = true; soundName = newMove.Sound_shield; } if (!newMove.AOE) break; //only hit one enemy } } //play sounds if (shieldHit) playRandomShieldHitSound(newMove.Disarming); else if (!enemyHit) playMissSound(); else playRandomHitSound(); }
/// <summary> /// This takes as input a position and a Ray and a maximum distance, then finds /// the first Block impacted by the Ray on this map, if any. Return types are /// through a large number of "out" parameters. Note it will never return the /// cell which contains the start of the Ray. /// /// Note: if successful is FALSE, the returned data will be garbage (since it's /// not easily nullable). So be aware of that. /// </summary> /// <param name="chunkX">The chunk(X) position to start the Ray from. This will be /// set to the chunk(X) position we end on.</param> /// <param name="chunkZ">The chunk(Z) position to start the Ray from. This will be /// set to the chunk(Z) position we end on.</param> /// <param name="lookRay">The Ray to look along.</param> /// <param name="maxDistance">The maximum distance along the ray that collisions /// will be considered. Uses the MAX distance.</param> /// <param name="requireVisible">Whether or not to skip invisible blocks.</param> /// <param name="requireImpassable">Whether or not to skip passable blocks.</param> /// <param name="foundBlock">The block that was actually found.</param> /// <param name="blockPosition">The in-chunk (integer) position of the block that was found.</param> /// <param name="faceTouched">The face that was first touched by the Ray.</param> /// <param name="successful">Whether ot not anything was found</param> public void BlockLookedAt(ref int chunkX, ref int chunkZ, Ray lookRay, int maxDistance, bool requireVisible, bool requireImpassable, out Block foundBlock, out Point3 blockPosition, out Face faceTouched, out bool successful) { if (lookRay.Position.Y < 0 || lookRay.Position.Y >= GameConstants.CHUNK_Y_HEIGHT) throw new ArgumentException("Can't cast rays from offscreen!"); successful = false; blockPosition = Point3.RoundDown(lookRay.Position); BoundingBox blockBounds = new BoundingBox( new Vector3(blockPosition.X, blockPosition.Y, blockPosition.Z), new Vector3(blockPosition.X + 1, blockPosition.Y + 1, blockPosition.Z + 1)); if (!blockBounds.Intersects(lookRay).HasValue) throw new NotImplementedException(); int xChange = Numerical.sign(lookRay.Direction.X); int yChange = Numerical.sign(lookRay.Direction.Y); int zChange = Numerical.sign(lookRay.Direction.Z); faceTouched = Face.FRONT; foundBlock = new Block(); while (blockPosition.Y >= 0 && blockPosition.Y < GameConstants.CHUNK_Y_HEIGHT) { bool canMoveX = (xChange != 0); bool canMoveY = (yChange != 0 && (blockPosition.Y + yChange >= 0 && blockPosition.Y + yChange < GameConstants.CHUNK_Y_HEIGHT)); bool canMoveZ = (zChange != 0); bool hitX = false; bool hitY = false; bool hitZ = false; BoundingBox oldBox = blockBounds; int hits = 0; #region Move and count hits... if (canMoveX) { BoundingBox box = new BoundingBox(oldBox.Min + new Vector3(xChange, 0, 0), oldBox.Max + new Vector3(xChange, 0, 0)); float? result = box.Intersects(lookRay); hitX = result.HasValue; if (hitX) { hits++; blockPosition.X += xChange; faceTouched = (xChange < 0 ? Face.RIGHT : Face.LEFT); blockBounds = box; if (Math.Abs(blockPosition.X - lookRay.Position.X) > maxDistance) return; } } if (canMoveY) { BoundingBox box = new BoundingBox(oldBox.Min + new Vector3(0, yChange, 0), oldBox.Max + new Vector3(0, yChange, 0)); float? result = box.Intersects(lookRay); hitY = result.HasValue; if (hitY) { hits++; blockPosition.Y += yChange; faceTouched = (yChange < 0 ? Face.TOP : Face.BOTTOM); blockBounds = box; if (Math.Abs(blockPosition.Y - lookRay.Position.Y) > maxDistance) return; } } if (canMoveZ) { BoundingBox box = new BoundingBox(oldBox.Min + new Vector3(0, 0, zChange), oldBox.Max + new Vector3(0, 0, zChange)); float? result = box.Intersects(lookRay); hitZ = result.HasValue; if (hitZ) { hits++; blockPosition.Z += zChange; faceTouched = (zChange < 0 ? Face.BACK : Face.FRONT); blockBounds = box; if (Math.Abs(blockPosition.Z - lookRay.Position.Z) > maxDistance) return; } } #endregion //We either hit a corner (yielding multiple matches) or ran off //the edge of the world. In either case, I'm OK with "no result." if (hits != 1) return; foundBlock = GetHighPriorityBlock(chunkX, chunkZ, blockPosition.X, blockPosition.Y, blockPosition.Z); if (BlockLookedAt_TestCompatibility(lookRay, requireVisible, requireImpassable, foundBlock, blockBounds)) { successful = true; HelperMethods.FixCoordinates(ref chunkX, ref chunkZ, ref blockPosition); return; } } }
//check with a bounding box public bool CheckBoundingSpheres(BoundingBox CheckArg) { for (int cntr = 0; cntr < MyModel.Meshes.Count; cntr++) { //creates a sphere for one mesh BoundingSphere Temp = this.MyModel.Meshes[cntr].BoundingSphere; //adjusts to center of the model Temp.Center += this.Position; if (CheckArg.Intersects(Temp)) { //intersection confimerd, stop checks and prevent model from moving in outer code return (true); } } //else, return false, no hit detected return (false); }
private float findIntersection(BoundingBox boundingBox) { Vector2 normalizedLaserDirection = Direction; normalizedLaserDirection.Normalize(); Ray laser_ray = new Ray(new Vector3(End, 0), new Vector3(normalizedLaserDirection, 0)); float? intersection = boundingBox.Intersects(laser_ray); if (intersection == null) { intersection = -1f; } return (float)intersection; }
// Updates Level. Returns true if Player has died, false otherwise. public virtual bool Update(BoundingBox bBoxPlayer, GameTime gameTime) { if (bBoxPlayer.Intersects(mLevelFinish)) { mIsCompleted = true; } foreach (Interactable i in mLevelInteractables.Values) i.Update(gameTime); // Check for possible interactions with Level Interactables. Check(bBoxPlayer); return false; }
private void checkExperienceGrabs() { foreach (Character player in currentLevel.players) { BoundingBox playerbox = new BoundingBox(new Vector3(player.getX(), player.getY() - player.height, Constants.CHARACTER_DEPTH), new Vector3(player.getX() + player.width, player.getY(), Constants.CHARACTER_DEPTH)); foreach (ExperienceOrb exp in expOrbs) { if (exp.isAlive) { BoundingBox expBox = new BoundingBox(new Vector3(exp.position.X, exp.position.Y - exp.height, Constants.CHARACTER_DEPTH), new Vector3(exp.position.X + exp.width, exp.position.Y, Constants.CHARACTER_DEPTH)); if (playerbox.Intersects(expBox)) { ((UserControlledCharacter)player).applyExperience(exp); exp.isAlive = false; break; } } } } }
public void Intersects(ref BoundingBox box, out PlaneIntersectionType result) { box.Intersects(ref this, out result); }
protected override void TryTalk() { switch (this.PlayerManager.Action) { case ActionType.Idle: case ActionType.Walking: case ActionType.Running: case ActionType.Sliding: if (this.PlayerManager.Background || !this.SpeechManager.Hidden || this.Npc.ActorType == ActorType.Owl && (this.OwlInvisible || this.CurrentAction == NpcAction.TakeOff || this.CurrentAction == NpcAction.Fly)) break; if (this.Npc.CustomSpeechLine == null) { if (this.InputManager.CancelTalk != FezButtonState.Pressed) break; Vector3 vector3_1 = Vector3.UnitY + (FezMath.SideMask(this.CameraManager.Viewpoint) + FezMath.DepthMask(this.CameraManager.Viewpoint)) * 1.5f; BoundingBox boundingBox = new BoundingBox(this.Position - vector3_1, this.Position + vector3_1); Vector3 mask = FezMath.GetMask(FezMath.VisibleAxis(this.CameraManager.Viewpoint)); Vector3 vector3_2 = FezMath.ForwardVector(this.CameraManager.Viewpoint); Ray ray = new Ray() { Position = this.PlayerManager.Center * (Vector3.One - mask) - vector3_2 * this.LevelManager.Size, Direction = vector3_2 }; float? nullable = boundingBox.Intersects(ray); if (!nullable.HasValue || this.TestObstruction(ray.Position, nullable.Value)) break; } this.Talk(); break; } }
public Room GetMostLikelyRoom(Voxel v) { Voxel vRef = v; foreach(Room r in DesignatedRooms.Where(r => r.ContainsVoxel(vRef))) { return r; } BoundingBox larger = new BoundingBox(v.GetBoundingBox().Min - new Vector3(0.5f, 0.5f, 0.5f), v.GetBoundingBox().Max + new Vector3(0.5f, 0.5f, 0.5f)); return (from room in BuildDesignations from buildDesignation in room.VoxelOrders where larger.Intersects(buildDesignation.Voxel.GetBoundingBox()) select buildDesignation.ToBuild).FirstOrDefault(); }
/// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { #region Keyboard control keyboardState = Keyboard.GetState(); #region Left Key if (keyboardState.IsKeyDown(Keys.Left)) { if (((WarGame)base.Game).CurrentScene is MainScene) { ((WarGame)base.Game).Camera.RotateLeft(); } } #endregion #region Right Key if (keyboardState.IsKeyDown(Keys.Right)) { if (((WarGame)base.Game).CurrentScene is MainScene) { ((WarGame)base.Game).Camera.RotateRight(); } } #endregion #region Up Key if (keyboardState.IsKeyDown(Keys.Up)) { if (((WarGame)base.Game).CurrentScene is MainScene) ((WarGame)base.Game).Camera.ZoomUp(); else if (((WarGame)base.Game).CurrentScene is MenuScene && !isUpKeyPressed) { isUpKeyPressed = true; (((WarGame)base.Game).CurrentScene as MenuScene).SwitchUp(); ((WarGame)base.Game).Sound.ClickSoundInstance.Play(); } } if (keyboardState.IsKeyUp(Keys.Up)) isUpKeyPressed = false; #endregion #region Down Key if (keyboardState.IsKeyDown(Keys.Down)) { if (((WarGame)base.Game).CurrentScene is MainScene) ((WarGame)base.Game).Camera.ZoomDown(); else if (((WarGame)base.Game).CurrentScene is MenuScene && !isDownKeyPressed) { isDownKeyPressed = true; (((WarGame)base.Game).CurrentScene as MenuScene).SwitchDown(); ((WarGame)base.Game).Sound.ClickSoundInstance.Play(); } } if(keyboardState.IsKeyUp(Keys.Down)) isDownKeyPressed = false; #endregion #region W Key if (keyboardState.IsKeyDown(Keys.W)) { if (((WarGame)base.Game).CurrentScene is MainScene) { ((WarGame)base.Game).Camera.MoveForward(); } } #endregion #region S Key if (keyboardState.IsKeyDown(Keys.S)) { if (((WarGame)base.Game).CurrentScene is MainScene) { ((WarGame)base.Game).Camera.MoveBackwards(); } } #endregion #region A Key and Left Ctrl key if (keyboardState.IsKeyDown(Keys.A)) { if (((WarGame)base.Game).CurrentScene is MainScene) { if (keyboardState.IsKeyDown(Keys.LeftControl)) { if ((!isAKeyPressed || !isCtrlKeyPressed)) { isAKeyPressed = true; isCtrlKeyPressed = true; ((WarGame)base.Game).Scene.ActivateAllFighters(); } } else ((WarGame)base.Game).Camera.MoveLeft(); } } if (keyboardState.IsKeyUp(Keys.A)) isAKeyPressed = false; if (keyboardState.IsKeyUp(Keys.LeftControl)) isCtrlKeyPressed = false; #endregion #region D Key if (keyboardState.IsKeyDown(Keys.D)) { if (((WarGame)base.Game).CurrentScene is MainScene) { ((WarGame)base.Game).Camera.MoveRight(); } } #endregion #region M Key if (keyboardState.IsKeyDown(Keys.M) && !isMKeyPressed) { if (((WarGame)base.Game).CurrentScene is MainScene) { isMKeyPressed = true; ((WarGame)base.Game).CurrentTechnique++; } } if (keyboardState.IsKeyUp(Keys.M)) isMKeyPressed = false; #endregion #region Enter key if (keyboardState.IsKeyDown(Keys.Enter)) { if (((WarGame)base.Game).CurrentScene is MenuScene) { (((WarGame)base.Game).CurrentScene as MenuScene).ExecuteAction(); ((WarGame)base.Game).Sound.PopSoundInstance.Play(); } } #endregion #region Escape Key if (keyboardState.IsKeyDown(Keys.Escape) && !isEscapePressed) { isEscapePressed = true; ((WarGame)base.Game).CurrentScene.ExecuteEscape(); } if (keyboardState.IsKeyUp(Keys.Escape)) isEscapePressed = false; #endregion #region P Key if (keyboardState.IsKeyDown(Keys.P) && !isPKeyPressed) { isPKeyPressed = true; if (((WarGame)base.Game).CurrentScene is MainScene) { ((WarGame)base.Game).Scene.TogglePause(); } } if (keyboardState.IsKeyUp(Keys.P)) isPKeyPressed = false; #endregion #region B Key if (keyboardState.IsKeyDown(Keys.B) && !isBKeyPressed) { isBKeyPressed = true; if (((WarGame)base.Game).CurrentScene is MainScene) { foreach (GameObject o in ((WarGame)base.Game).Scene.SceneObjects) { o.DebugModeToggle(); } ((WarGame)base.Game).Scene.IsInDebugMode = !((WarGame)base.Game).Scene.IsInDebugMode; } } if (keyboardState.IsKeyUp(Keys.B)) isBKeyPressed = false; #endregion #region F Key if (keyboardState.IsKeyDown(Keys.F) && !isFKeyPressed) { isFKeyPressed = true; ((WarGame)base.Game).Graphics.ToggleFullScreen(); ((WarGame)base.Game).UpdateMenuItemsPositions(); } if (keyboardState.IsKeyUp(Keys.F)) isFKeyPressed = false; #endregion #region C Key if (keyboardState.IsKeyDown(Keys.C)) { if (((WarGame)base.Game).CurrentScene is MainScene && ((WarGame)base.Game).Scene.HumanBase == null) { Ray directionRay = GetTheCurrentMouseRay(); Nullable<float> d = directionRay.Intersects(((WarGame)base.Game).Scene.GroundElement.BoundingBox); if (d != null) { float distance = (float)d; mouseClickPosition = directionRay.Position + directionRay.Direction * distance; Building b = new Building(((WarGame)base.Game), new Vector3(mouseClickPosition.X, ((WarGame)base.Game).Scene.GroundYAxisPosition + 2.0f, mouseClickPosition.Z), ((WarGame)base.Game).Scene); if (b.CheckForCollisions() == null) { ((WarGame)base.Game).Scene.HumanBase = b; ((WarGame)base.Game).Scene.SceneComponents.Add(b); ((WarGame)base.Game).Scene.SceneObjects.Add(b); } else b.Destroy(); mouseClickPosition = V3Extensions.CreateInvalidVector(); mouseReleasePosition = V3Extensions.CreateInvalidVector(); } } } #endregion #endregion #region Mouse control mouseState = Mouse.GetState(); #region Left mouse button #region LMB click if (mouseState.LeftButton == ButtonState.Pressed && !isLeftMousePressed && ((WarGame)base.Game).CurrentScene is MainScene) { isLeftMousePressed = true; Ray directionRay = GetTheCurrentMouseRay(); Nullable<float> d = directionRay.Intersects(((WarGame)base.Game).Scene.GroundElement.BoundingBox); if (d != null) { float distance = (float)d; mouseClickPosition = directionRay.Position + directionRay.Direction * distance; } } #endregion #region LMB scrolling if (mouseState.LeftButton == ButtonState.Pressed && isLeftMousePressed && ((WarGame)base.Game).CurrentScene is MainScene) { Ray directionRay = GetTheCurrentMouseRay(); Nullable<float> d = directionRay.Intersects(((WarGame)base.Game).Scene.GroundElement.BoundingBox); if (d != null) { float distance = (float)d; mouseReleasePosition = directionRay.Position + directionRay.Direction * distance; //drawing selection rectangle ((WarGame)base.Game).Scene.SelectionRectangle.Show(); } } #endregion #region LMB releasing if (mouseState.LeftButton == ButtonState.Released && isLeftMousePressed && ((WarGame)base.Game).CurrentScene is MainScene) { isLeftMousePressed = false; // if the click and release points are far enough each other than it is scrolling if ((mouseClickPosition - mouseReleasePosition).LengthSquared() > leftMouseClickCriticalRadius) { // creating the selection bounding box BoundingBox box = new BoundingBox(new Vector3( Math.Min(mouseClickPosition.X, mouseReleasePosition.X), selectionBoundingBoxMinimalYValue, Math.Min(mouseClickPosition.Z, mouseReleasePosition.Z)), new Vector3( Math.Max(mouseClickPosition.X, mouseReleasePosition.X), selectionBoundingBoxMaximalYValue, Math.Max(mouseClickPosition.Z, mouseReleasePosition.Z))); ((WarGame)base.Game).Scene.DisactivateAllFighters(); // activating the figters inside the selection bounding box foreach (Fighter f in ((WarGame)base.Game).Scene.Fighters) { if (box.Intersects(f.BoundingBox)) { f.Activate(); ((WarGame)base.Game).Scene.ActiveFighters.Add(f); } } // restaring the mouse click and release positions mouseClickPosition = V3Extensions.CreateInvalidVector(); mouseReleasePosition = V3Extensions.CreateInvalidVector(); // hiding selection rectangle ((WarGame)base.Game).Scene.SelectionRectangle.Hide(); } // in any other case it is single-click else { Ray directionRay = GetTheCurrentMouseRay(); Nullable<float> minDistance = float.MaxValue; GameObject closestObject = null; // finding the object which is closest to the user foreach (GameObject g in ((WarGame)base.Game).Scene.SceneObjects) { Nullable<float> d = directionRay.Intersects(g.BoundingBox); if (d != null && d < minDistance) { closestObject = g; minDistance = d; } } // reaction depends on the type of the closes object if (closestObject != null) { switch (closestObject.GetType().Name) { case "Fighter": ((WarGame)base.Game).Scene.DisactivateAllFighters(); ((WarGame)base.Game).Scene.ActiveFighters.Add((Fighter)closestObject); ((Fighter)closestObject).Activate(); break; case "AlienCraft": foreach (Fighter f in ((WarGame)base.Game).Scene.ActiveFighters) { f.CurrentSB = SBNames.Attack; f.TargetToAttack = (AlienCraft)closestObject; f.Target = V3Extensions.CreateInvalidVector(); } break; case "GroundElement": foreach (Fighter f in ((WarGame)base.Game).Scene.ActiveFighters) { f.CurrentSB = SBNames.SeekWithSeparation; f.Target = directionRay.Position + directionRay.Direction * (float)minDistance + new Vector3(0, 1, 0); f.TargetToAttack = null; } break; } } } } #endregion #endregion #region Right mouse button #region RMB click if (mouseState.RightButton == ButtonState.Pressed && ((WarGame)base.Game).CurrentScene is MainScene) { ((WarGame)base.Game).Scene.DisactivateAllFighters(); } #endregion #endregion bool isMenuEnabled = ((WarGame)base.Game).CurrentScene is MainMenu; if (isMenuEnabled == true && ((WarGame)base.Game).IsMouseVisible) ((WarGame)base.Game).IsMouseVisible = false; else if (isMenuEnabled == false && !((WarGame)base.Game).IsMouseVisible) ((WarGame)base.Game).IsMouseVisible = true; #endregion base.Update(gameTime); }
private void TrackGroupConnectivePath(int groupId) { Vector3 vector3_1 = FezMath.ScreenSpaceMask(this.CameraManager.Viewpoint); Vector3 b = FezMath.Abs(FezMath.ForwardVector(this.CameraManager.Viewpoint)); this.connectedAos.Clear(); foreach (ArtObjectInstance artObjectInstance in this.LevelMaterializer.LevelArtObjects) { int? attachedGroup = artObjectInstance.ActorSettings.AttachedGroup; int num = groupId; if ((attachedGroup.GetValueOrDefault() != num ? 0 : (attachedGroup.HasValue ? 1 : 0)) != 0) this.connectedAos.Add(artObjectInstance); } foreach (ArtObjectInstance artObjectInstance1 in this.connectedAos) { if (artObjectInstance1.ActorSettings.NextNode.HasValue) artObjectInstance1.ActorSettings.NextNodeAo = this.LevelManager.ArtObjects[artObjectInstance1.ActorSettings.NextNode.Value]; foreach (ArtObjectInstance artObjectInstance2 in this.connectedAos) { if (artObjectInstance2.ActorSettings.NextNode.HasValue && artObjectInstance2.ActorSettings.NextNode.Value == artObjectInstance1.Id) artObjectInstance1.ActorSettings.PrecedingNodeAo = artObjectInstance2; } } TrileGroup group; if (!this.LevelManager.Groups.TryGetValue(groupId, out group)) { Logger.Log("MovingGroupsHost::TrackGroupConnectivePath", LogSeverity.Warning, "Node is connected to a group that doesn't exist!"); } else { if (group.MoveToEnd) { ArtObjectInstance artObjectInstance1 = (ArtObjectInstance) null; foreach (ArtObjectInstance artObjectInstance2 in this.connectedAos) { if (!artObjectInstance2.ActorSettings.NextNode.HasValue && artObjectInstance2.ArtObject.ActorType == ActorType.ConnectiveRail) { artObjectInstance1 = artObjectInstance2; break; } } if (artObjectInstance1 == null) throw new InvalidOperationException("No end-node! Can't move to end."); Vector3 zero = Vector3.Zero; foreach (TrileInstance trileInstance in group.Triles) zero += trileInstance.Center; Vector3 vector3_2 = zero / (float) group.Triles.Count; Vector3 ordering = artObjectInstance1.Position - vector3_2; group.Triles.Sort((IComparer<TrileInstance>) new MovingTrileInstanceComparer(ordering)); foreach (TrileInstance instance in group.Triles) { instance.Position += ordering; this.LevelManager.UpdateInstance(instance); } } BoundingBox boundingBox1 = new BoundingBox(new Vector3(float.MaxValue), new Vector3(float.MinValue)); Vector3 zero1 = Vector3.Zero; foreach (TrileInstance trileInstance in group.Triles) { Vector3 vector3_2 = trileInstance.TransformedSize / 2f; boundingBox1.Min = Vector3.Min(boundingBox1.Min, (trileInstance.Center - vector3_2) * vector3_1); boundingBox1.Max = Vector3.Max(boundingBox1.Max, (trileInstance.Center + vector3_2) * vector3_1 + b); zero1 += trileInstance.Center; } Vector3 vector3_3 = zero1 / (float) group.Triles.Count; BoundingBox boundingBox2 = new BoundingBox(); foreach (ArtObjectInstance artObjectInstance in this.connectedAos) { if (artObjectInstance.ArtObject.ActorType == ActorType.None) { Vector3 vector3_2 = artObjectInstance.Scale * artObjectInstance.ArtObject.Size / 2f; boundingBox2 = new BoundingBox(artObjectInstance.Position - vector3_2, artObjectInstance.Position + vector3_2); Quaternion rotation = artObjectInstance.Rotation; FezMath.RotateOnCenter(ref boundingBox2, ref rotation); boundingBox2.Min *= vector3_1; boundingBox2.Max = boundingBox2.Max * vector3_1 + b; if (boundingBox1.Intersects(boundingBox2)) break; } } ArtObjectInstance artObjectInstance3 = (ArtObjectInstance) null; foreach (ArtObjectInstance artObjectInstance1 in this.connectedAos) { if (artObjectInstance1.ArtObject.ActorType == ActorType.ConnectiveRail) { Vector3 vector3_2 = artObjectInstance1.Scale * artObjectInstance1.ArtObject.Size / 2f; BoundingBox box = new BoundingBox((artObjectInstance1.Position - vector3_2) * vector3_1, (artObjectInstance1.Position + vector3_2) * vector3_1 + b); if (boundingBox2.Intersects(box)) { artObjectInstance3 = artObjectInstance1; break; } } } if (artObjectInstance3 == null) { InvalidOperationException operationException = new InvalidOperationException("Nodeless branch!"); Logger.Log("Connective Groups", LogSeverity.Warning, operationException.Message); throw operationException; } else { ArtObjectInstance artObjectInstance1; for (; artObjectInstance3.ActorSettings.PrecedingNodeAo != null; artObjectInstance3 = artObjectInstance3.ActorSettings.PrecedingNodeAo) { Vector3 a = artObjectInstance3.ActorSettings.PrecedingNodeAo.Position - artObjectInstance3.Position; if ((double) Math.Abs(FezMath.Dot(a, b)) <= (double) Math.Abs(FezMath.Dot(a, FezMath.XZMask - b))) { bool flag = false; Vector3 point = a / 2f + artObjectInstance3.Position; foreach (ArtObjectInstance artObjectInstance2 in this.connectedAos) { if (artObjectInstance2.ArtObject.ActorType == ActorType.None) { Vector3 vector3_2 = artObjectInstance2.Scale * artObjectInstance2.ArtObject.Size / 2f; BoundingBox boundingBox3 = new BoundingBox(artObjectInstance2.Position - vector3_2, artObjectInstance2.Position + vector3_2); Quaternion rotation = artObjectInstance2.Rotation; FezMath.RotateOnCenter(ref boundingBox3, ref rotation); if (boundingBox3.Contains(point) != ContainmentType.Disjoint) { flag = true; break; } } } if (!flag) { artObjectInstance1 = artObjectInstance3; goto label_72; } } } artObjectInstance1 = artObjectInstance3; label_72: Vector3 ordering = artObjectInstance1.Position - vector3_3; group.Triles.Sort((IComparer<TrileInstance>) new MovingTrileInstanceComparer(ordering)); foreach (TrileInstance instance in group.Triles) { instance.Position += ordering; this.LevelManager.UpdateInstance(instance); } MovementPath movementPath = new MovementPath() { EndBehavior = PathEndBehavior.Bounce }; ArtObjectInstance artObjectInstance4 = artObjectInstance1; PathSegment pathSegment1 = (PathSegment) null; while (true) { ArtObjectInstance nextNodeAo = artObjectInstance4.ActorSettings.NextNodeAo; if (nextNodeAo != null) { Vector3 a = nextNodeAo.Position - artObjectInstance4.Position; bool flag1 = (double) Math.Abs(FezMath.Dot(a, b)) > (double) Math.Abs(FezMath.Dot(a, FezMath.XZMask - b)); bool flag2 = false; Vector3 point = a / 2f + artObjectInstance4.Position; foreach (ArtObjectInstance artObjectInstance2 in this.connectedAos) { if (artObjectInstance2.ArtObject.ActorType == ActorType.None) { Vector3 vector3_2 = artObjectInstance2.Scale * artObjectInstance2.ArtObject.Size / 2f; BoundingBox boundingBox3 = new BoundingBox(artObjectInstance2.Position - vector3_2, artObjectInstance2.Position + vector3_2); Quaternion rotation = artObjectInstance2.Rotation; FezMath.RotateOnCenter(ref boundingBox3, ref rotation); if (boundingBox3.Contains(point) != ContainmentType.Disjoint) { flag2 = true; break; } } } if (flag2 || flag1) { PathSegment pathSegment2 = nextNodeAo.ActorSettings.Segment.Clone(); pathSegment2.Destination = (pathSegment1 == null ? Vector3.Zero : pathSegment1.Destination) + nextNodeAo.Position - artObjectInstance4.Position; if (!flag2) pathSegment2.Duration = TimeSpan.Zero; movementPath.Segments.Add(pathSegment2); pathSegment1 = pathSegment2; artObjectInstance4 = nextNodeAo; } else break; } else break; } group.Path = movementPath; MovingGroupsHost.MovingGroupState movingGroupState = new MovingGroupsHost.MovingGroupState(group, true) { Enabled = false }; this.trackedGroups.Add(movingGroupState); if (group.MoveToEnd) { group.MoveToEnd = false; movingGroupState.MoveToEnd(); } foreach (ArtObjectInstance artObjectInstance2 in this.connectedAos) artObjectInstance2.Enabled = true; } } }
public BuildRoomOrder GetMostLikelyDesignation(Voxel v) { BoundingBox larger = new BoundingBox(v.GetBoundingBox().Min - new Vector3(0.5f, 0.5f, 0.5f), v.GetBoundingBox().Max + new Vector3(0.5f, 0.5f, 0.5f)); return (from room in BuildDesignations from buildDesignation in room.VoxelOrders where larger.Intersects(buildDesignation.Voxel.GetBoundingBox()) select room).FirstOrDefault(); }
public bool Intersects(BoundingBox box) { return(box.Intersects(this)); }
bool IsInViewFrustumWithNoFarClipping(BoundingBox box, BoundingFrustum viewFrustum) { // TODO: this causes a lot of allocations - maybe use a extension method with custom iterator? // Actually, the lambda below also generates allocations. Maybe unroll this? Not sure what // perf improvement that would have, if any var planes = new [] { viewFrustum.Near, viewFrustum.Left, viewFrustum.Right, viewFrustum.Top, viewFrustum.Bottom}; return planes.All(plane => box.Intersects(plane) != PlaneIntersectionType.Front); }
protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); X = "X:"; X += modelPosition.X; Y = "Y:"; Y += modelPosition.Y; Z = "Z:"; Z += modelPosition.Z; boundingBoxChar = new BoundingBox(new Vector3(modelPosition.X - 10, modelPosition.Y, modelPosition.Z - 10), new Vector3(modelPosition.X + 10, modelPosition.Y + 50, modelPosition.Z + 10)); BoundingBoxBlock = new BoundingBox(new Vector3(- 110, -10, - 110), new Vector3(110, 50, 110)); if (boundingBoxChar.Intersects(BoundingBoxBlock)) { if (modelPosition.Z <= -109) { modelVelocity.Z -= 3; } if (modelPosition.Z >= 109) { modelVelocity.Z += 3; } if (modelPosition.X <= -109) { modelVelocity.X -= 3; } if (modelPosition.X >= 109) { modelVelocity.X += 3; } } /*for(int i = 0; i < block.Meshes.Count; i++) { BoundingSphere c1BoundingSphere = block.Meshes[i].BoundingSphere; c1BoundingSphere.Center += modelPosition; for (int j = 0; j < myModel.Meshes.Count; j++) { BoundingSphere c2BoundingSphere = myModel.Meshes[j].BoundingSphere; c2BoundingSphere.Center += modelPosition; if (!c1BoundingSphere.Intersects(c2BoundingSphere)) { modelPosition.Z += 20; break; } } }*/ // Get some input. UpdateInput(gameTime); // Add velocity to the current position. modelPosition += modelVelocity; // Bleed off velocity over time. modelVelocity *= 0.0f; base.Update(gameTime); }
//----------------------- Feng ------------------------------------------------ // 检测车辆是否碰到了障碍物 private bool CheckCollision(Hazard theHazard) { // 分别计算并使用封闭(包裹)盒给障碍物和车 BoundingBox aHazardBox = new BoundingBox(new Vector3(theHazard.Position.X, theHazard.Position.Y, 0), new Vector3(theHazard.Position.X + (mHazard.Width * .2f), theHazard.Position.Y + ((mHazard.Height - 50) * .2f), 0)); BoundingBox aCarBox = new BoundingBox(new Vector3(mCarPosition.X, mCarPosition.Y, 0), new Vector3(mCarPosition.X + (mCar.Width * .2f), mCarPosition.Y + (mCar.Height * .2f), 0)); if (aHazardBox.Intersects(aCarBox) == true) // 碰上了吗? { mCurrentState = State.Crash; mCarsRemaining -= 1; if (mCarsRemaining < 0) { mCurrentState = State.GameOver; mExitCountDown = 10; } return true; } return false; }
void CheckForCollision() { BoundingBox bb1 = new BoundingBox(new Vector3(spritePosition1.X - (sprite1Width / 2), spritePosition1.Y - (sprite1Height / 2), 0), new Vector3(spritePosition1.X + (sprite1Width / 2), spritePosition1.Y + (sprite1Height / 2), 0)); BoundingBox bb2 = new BoundingBox(new Vector3(spritePosition2.X - (sprite2Width / 2), spritePosition2.Y - (sprite2Height / 2), 0), new Vector3(spritePosition2.X + (sprite2Width / 2), spritePosition2.Y + (sprite2Height / 2), 0)); if (bb1.Intersects(bb2)) { soundEffect.Play(); } }
//closest colliding wall to a bomb within a bounding box private float ClosestCollidingWallOrBlock(Bomb b, BoundingBox bB) { float max = (float)b.ExplosionLength; float temp; for (int i = 0; i < m_Walls.Count; i++) { if (bB.Intersects(m_Walls[i].BoundingBox)) { temp = Vector3.Distance(b.Position, m_Walls[i].Position); if (temp < max) { max = temp; } } } for (int i = 0; i < m_Blocks.Count; i++) { if (bB.Intersects(m_Blocks[i].BoundingBox)) { temp = Vector3.Distance(b.Position, m_Blocks[i].Position); if (temp < max) { max = temp; } } } return max; }
public ValveState(ValvesBoltsTimeswitchesHost host, ArtObjectInstance ao) { ServiceHelper.InjectServices((object) this); this.Host = host; this.ArtObject = ao; this.IsBolt = this.ArtObject.ArtObject.ActorType == ActorType.BoltHandle; this.IsTimeswitch = this.ArtObject.ArtObject.ActorType == ActorType.Timeswitch; BoundingBox boundingBox = new BoundingBox(this.ArtObject.Position - this.ArtObject.ArtObject.Size / 2f, this.ArtObject.Position + this.ArtObject.ArtObject.Size / 2f); if (this.ArtObject.ActorSettings.AttachedGroup.HasValue) this.AttachedGroup = this.LevelManager.Groups[this.ArtObject.ActorSettings.AttachedGroup.Value]; if (this.IsTimeswitch) { this.eTimeswitchWindBack = SoundEffectExtensions.EmitAt(this.Host.TimeswitchWindBackSound, ao.Position, true, true); foreach (ArtObjectInstance artObjectInstance in (IEnumerable<ArtObjectInstance>) this.LevelManager.ArtObjects.Values) { if (artObjectInstance != ao && artObjectInstance.ArtObject.ActorType == ActorType.TimeswitchMovingPart) { BoundingBox box = new BoundingBox(artObjectInstance.Position - artObjectInstance.ArtObject.Size / 2f, artObjectInstance.Position + artObjectInstance.ArtObject.Size / 2f); if (boundingBox.Intersects(box)) { this.TimeswitchScrewAo = artObjectInstance; break; } } } } int num1; if (!this.IsBolt && !this.IsTimeswitch && (this.GameState.SaveData.ThisLevel.PivotRotations.TryGetValue(this.ArtObject.Id, out num1) && num1 != 0)) { int num2 = Math.Abs(num1); int num3 = Math.Sign(num1); for (int index = 0; index < num2; ++index) this.ArtObject.Rotation *= Quaternion.CreateFromAxisAngle(Vector3.UnitY, 1.570796f * (float) num3); } if (this.IsBolt) { foreach (TrileInstance instance in this.AttachedGroup.Triles) instance.PhysicsState = new InstancePhysicsState(instance); } foreach (Volume volume in (IEnumerable<Volume>) this.LevelManager.Volumes.Values) { Vector3 vector3 = FezMath.Abs(volume.To - volume.From); if ((double) vector3.X == 3.0 && (double) vector3.Z == 3.0 && ((double) vector3.Y == 1.0 && boundingBox.Contains(volume.BoundingBox) == ContainmentType.Contains)) { this.CenterOffset = (volume.From + volume.To) / 2f - this.ArtObject.Position; break; } } }
public void colisao(List<Inimigo> inimigos) { for (int i = 0; i < inimigos.Count; i++) { Vector3 A = new Vector3(positionPlayer.X+5, positionPlayer.Y, 0); Vector3 B = new Vector3(positionPlayer.X + 44, positionPlayer.Y + imgPlayer.Height, 0); Vector3 C = new Vector3(inimigos[i].positionInimigo.X, inimigos[i].positionInimigo.Y+10, 0); Vector3 D = new Vector3(inimigos[i].positionInimigo.X + inimigos[i].largura, inimigos[i].positionInimigo.Y + inimigos[i].imgInimigo.Height-13, 0); BoundingBox boxPlayer = new BoundingBox(A, B); BoundingBox boxEnemy = new BoundingBox(C, D); if (boxPlayer.Intersects(boxEnemy)) { screen.removeComponent(inimigos[i]); screen.inimigos.Remove(inimigos[i]); screen.addComponent(new Explosao(mygame, C, 2, screen)); if (hp > 0) { hp--; } else { vida--; hp = 5; screen.addComponent(new Explosao(mygame, new Vector3(screen.player.positionPlayer.X, screen.player.positionPlayer.Y, 0), 2, screen)); } if (vida > 0) { vida--; } else { screen.removeComponent(this); mygame.setScreen(new ScreenSplash(mygame)); } } } }
public void Contains(ref BoundingBox box, out ContainmentType result) { bool flag = false; PlaneIntersectionType result1; box.Intersects(ref this.near, out result1); if (result1 == PlaneIntersectionType.Front) { result = ContainmentType.Disjoint; } else { if (result1 == PlaneIntersectionType.Intersecting) { flag = true; } box.Intersects(ref this.left, out result1); if (result1 == PlaneIntersectionType.Front) { result = ContainmentType.Disjoint; } else { if (result1 == PlaneIntersectionType.Intersecting) { flag = true; } box.Intersects(ref this.right, out result1); if (result1 == PlaneIntersectionType.Front) { result = ContainmentType.Disjoint; } else { if (result1 == PlaneIntersectionType.Intersecting) { flag = true; } box.Intersects(ref this.top, out result1); if (result1 == PlaneIntersectionType.Front) { result = ContainmentType.Disjoint; } else { if (result1 == PlaneIntersectionType.Intersecting) { flag = true; } box.Intersects(ref this.bottom, out result1); if (result1 == PlaneIntersectionType.Front) { result = ContainmentType.Disjoint; } else { if (result1 == PlaneIntersectionType.Intersecting) { flag = true; } box.Intersects(ref this.far, out result1); if (result1 == PlaneIntersectionType.Front) { result = ContainmentType.Disjoint; } else { if (result1 == PlaneIntersectionType.Intersecting) { flag = true; } result = flag ? ContainmentType.Intersects : ContainmentType.Contains; } } } } } } }