Example #1
0
        public void GetCollisions()
        {
            RemoveDeletedEntities();

            // Sort all entities by their minimum X extent
            Compatible.Sort((e1, e2) =>
                            e1.GetComponent <CircleColliderComponent>().MinX()
                            .CompareTo(
                                e2.GetComponent <CircleColliderComponent>().MinX()
                                )
                            );

            // Reset collision info
            for (int i = 0; i < Compatible.Count; i++)
            {
                CircleColliderComponent collider  = Compatible[i].GetComponent <CircleColliderComponent>();
                TransformComponent      transform = Compatible[i].GetComponent <TransformComponent>();

                collider.UpdatePosition(transform);
                collider.ClearCollisions();
            }

            Collisions.Clear();

            for (int i = 0; i < Compatible.Count; i++)
            {
                CircleColliderComponent collider = Compatible[i].GetComponent <CircleColliderComponent>();
                float maxX = collider.MaxX();
                for (int j = i + 1; j < Compatible.Count; j++)
                {
                    CircleColliderComponent otherCollider = Compatible[j].GetComponent <CircleColliderComponent>();

                    // If the other collider has a minimum x span that is greater than our max x,
                    // Then we no longer need to keep checking. This collider and all other colliders after it cannot be intersecting this collider.

                    if (otherCollider.MinX() > maxX)
                    {
                        break;
                    }



                    if (collider.Intersects(otherCollider))
                    {
                        if (!_shouldDetectCollision(Compatible[i], Compatible[j]))
                        {
                            continue;
                        }
                        //Calculatye the collison normal

                        var collNormal = otherCollider.Position - collider.Position;

                        if (collNormal != Vector2.Zero)
                        {
                            collNormal.Normalize();
                        }
                        else
                        {
                            collNormal = Vector2.One;
                        }

                        Collisions.Add(new Collision()
                        {
                            Normal = collNormal,
                            E1     = Compatible[i],
                            E2     = Compatible[j]
                        });
                    }
                }
            }
        }