public bool CollidesWithCollider(ICollider collider, out ICollider colliderB, int layer) { if (!collider.Active) { colliderB = null; return(false); } foreach (var otherCollider in _collidersInArea) { if (otherCollider.Layer == layer) { if (collider != otherCollider) { if (otherCollider.Active) { if (collider.Intersects(otherCollider)) { colliderB = otherCollider; return(true); } } } } } colliderB = null; return(false); }
public void CheckCollision(ICollider collider) { foreach (var otherCollider in _collidersInArea) { if (collider != otherCollider) { if (collider.Intersects(otherCollider)) { float totalInverseMass = collider.Particle.InvertedMass + otherCollider.Particle.InvertedMass;; // Generate Contact Data // relative velocity Vector2 relativeVelocity = otherCollider.Particle.Velocity - collider.Particle.Velocity; Vector2 direction = otherCollider.Particle.Position - collider.Particle.Position; Vector2 normal = new Vector2(-direction.X, -direction.Y); normal.Normalize(); float velocityAlongNormal = Vector2.Dot(relativeVelocity, normal); if (velocityAlongNormal > 0) { return; } float e = Math.Min(collider.Particle.Restitution, otherCollider.Particle.Restitution); float j = -(1 + e) * velocityAlongNormal; j /= totalInverseMass; // Apply Impulse Vector2 impulse = j * normal; if (!float.IsNaN(impulse.X) && !float.IsNaN(impulse.Y)) { collider.Particle.Velocity -= (collider.Particle.InvertedMass * impulse); collider.Particle.RevertPosition(); otherCollider.Particle.Velocity += (otherCollider.Particle.InvertedMass * impulse); otherCollider.Particle.RevertPosition(); } } } } }
public void ResolveVelocity(ICollider collider) { foreach (var otherCollider in _collidersInArea) { if (!otherCollider.Active) { return; } if (collider != otherCollider) { if (collider.Intersects(otherCollider)) { Vector2 direction = otherCollider.Particle.Position - collider.Particle.Position; Vector2 normal = new Vector2(-direction.X, -direction.Y); normal.Normalize(); Vector2 seperatingVelocity = CalculateSeperatingVelocity(collider.Particle, otherCollider.Particle, normal); if (seperatingVelocity.Length() > 0) { return; } float e = Math.Min(collider.Particle.Restitution, otherCollider.Particle.Restitution); Vector2 newSepVelocity = -seperatingVelocity * e; Vector2 deltaVelocity = newSepVelocity - seperatingVelocity; float totalInverseMass = collider.Particle.InvertedMass + otherCollider.Particle.InvertedMass;; if (totalInverseMass <= 0) { return; } Vector2 impulse = deltaVelocity / totalInverseMass; Vector2 impulsePerIMass = normal * impulse; collider.Particle.Velocity += impulsePerIMass * collider.Particle.InvertedMass; collider.Particle.Velocity -= impulsePerIMass * collider.Particle.InvertedMass; } } } }