private bool CollidsWith(Animal sprite1, Animal sprite2) { try { Rect r1 = Bounds(sprite1); Rect r2 = Bounds(sprite2); if (r1.IntersectsWith(r2)) { return true; } else { return false; } } catch { } return false; // we should not get here }
private Rect Bounds(Animal sprite) { Point ptBottomRight = new Point(sprite.Position.X + sprite.RenderSize.Width, sprite.Position.Y + sprite.RenderSize.Height); return new Rect(sprite.Position, ptBottomRight); }
private void CheckForAnimalCollision(Animal animal) { foreach (Animal anim in MyCanvas.Children) { Point newPosition = new Point(animal.Position.X + animal.Velocity.X, animal.Position.Y + animal.Velocity.Y); Point newVelocity = animal.Velocity; if (anim.ColideCountDown == 0) { anim.Collided = false; //anim.StatusColor = "#FF008000"; } if (animal.ColideCountDown == 0) { animal.Collided = false; //animal.StatusColor = "#FF008000"; } if (CollidsWith(animal, anim) && anim != animal) { if (anim.Collided == false) { newVelocity.Y = -newVelocity.Y; newVelocity.X = -newVelocity.X; //anim.StatusColor = "#FFFF0000"; //animal.StatusColor = "#FFFF0000"; anim.SetCollideCountDown(); anim.Collided = true; if (CageControlModel.CageStress >= 0) { CageControlModel.CageStress += (2 / anim.StressTolerance); } } } else { if (!CageControlModel.AnimalsAreFree) { //Wall detection if (newPosition.X + animal.ActualWidth >= MyCanvas.ActualWidth) { newPosition.X = MyCanvas.ActualWidth - animal.ActualWidth; newVelocity.X = -newVelocity.X; } else if (newPosition.X <= 0) { newPosition.X = 0; newVelocity.X = -newVelocity.X; } if (newPosition.Y + animal.ActualHeight >= MyCanvas.ActualHeight) { newPosition.Y = MyCanvas.ActualHeight - animal.ActualHeight; newVelocity.Y = -newVelocity.Y; } else if (newPosition.Y <= 0) { newPosition.Y = 0; newVelocity.Y = -newVelocity.Y; } } } if (anim.ColideCountDown > 0) { anim.SubtractCountDown(); } if (animal.ColideCountDown > 0) { animal.SubtractCountDown(); } // Update the Animals's velocity and position. animal.Velocity = newVelocity; animal.Position = newPosition; } }