protected override bool CheckCollision(IDisplayableEntity entity1, IDisplayableEntity entity2) { // Get bounds of entity 1. Rectangle entity1Bounds = new Rectangle { X = (int)entity1.Position.Value.X, Y = (int)entity1.Position.Value.Y, Height = entity1.Height, Width = entity1.Width }; // Get bounds of entity 2. Rectangle entity2Bounds = new Rectangle { X = (int)entity2.Position.Value.X, Y = (int)entity2.Position.Value.Y, Height = entity2.Height, Width = entity2.Width }; // Check if the entity bounds intersect. if (entity1Bounds.Intersects(entity2Bounds)) { return(true); } return(false); }
protected override bool CheckCollision(IDisplayableEntity entity1, IDisplayableEntity entity2) { // Calculate the radius of the entities. float r1 = (entity1.Scale * entity1.Width) / 2; float r2 = (entity2.Scale * entity2.Width) / 2; // Check if the distance between the vectors is less than the radii. if (Vector3.Distance(entity1.Position.Value, entity2.Position.Value) < (r1 + r2)) { return(true); } return(false); }
/// <summary> /// Collision component update method. /// </summary> /// <param name="gameTime">Snapshot of elapsed time values.</param> public void Update(GameTime gameTime) { // Get entities. IReadOnlyList <IDisplayableEntity> entities = this.entities.Values.ToList(); // Run through entities and check if they collide. // Condition to terminate is list size - 1, because the last entity will already have been // checked with the other entities; this saves a wasteful iteration. for (int i = 0; i < entities.Count - 1; i++) { // Get entity 1. IDisplayableEntity entity1 = entities.ElementAt(i); // Run through the other entities to check against. // Here the loop count is i + 1, because we want to skip entities already checked and avoid checking // against itself: // i.e. entity index 0 is checked with index 3, when index 3 is being iterated in the main loop, // setting it to i + 1 means it will start checking index 3 against index 4; // this saves many wasteful iterations. for (int j = i + 1; j < entities.Count; j++) { // Get entity 2. IDisplayableEntity entity2 = entities.ElementAt(j); // Check if entities collide. if (CheckCollision(entity1, entity2)) { // If entity is collidable, call on collide. if (entity1 is ICollidable) { ((ICollidable)entity1).OnCollide(entity2); } if (entity2 is ICollidable) { ((ICollidable)entity2).OnCollide(entity1); } } } } }
/// <summary> /// The method to use to check for collision between two entities. /// </summary> /// <param name="entity1"></param> /// <param name="entity2"></param> /// <returns>True if entities have collided, false otherwise.</returns> protected abstract bool CheckCollision(IDisplayableEntity entity1, IDisplayableEntity entity2);