0
\$\begingroup\$

I'm building a game engine (for learning and self-development purpose), and I'm starting implementing collision resolution, I already have the collision detection part but I cant' find any good article or post about that and how to achieve it in details.

Here's my code for the collision detection:

That's the method called in the Update method, the Engine holds a list of BoxColliders called Colliders

private void CollisionDetection()
{
    foreach (BoxCollider boxCollider in Colliders)
    {
        if (!boxCollider.Collider.HasValue) continue;

        var collider1 = (Rectangle) boxCollider.Collider;
        foreach (BoxCollider boxCollider2 in Colliders.Where(x => !x.Guid.Equals(boxCollider.Guid)))
        {
            if (!boxCollider2.Collider.HasValue) continue;
            var collider2 = (Rectangle) boxCollider2.Collider;

            if (collider1.Intersects(collider2))
                boxCollider.OnCollision(boxCollider2);
        }
    }
}

And here's the OnCollision(BoxCollider other) method :

public void OnCollision(BoxCollider other)
{
    if (other.Collider == null || Collider == null) return;

    var rect = (Rectangle) other.Collider;
    var intersect = Rectangle.Intersect(Collider.Value, rect);

    // TODO : Resolve collision
}

I also have basic physic in the Engine so I would like a falling object to stop falling if it is against another collider.

In the case of a player walking on the ground, I guess the ground should apply an opposite force to the player if it collides ?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

If you have a constant gravity being applied to your entity in your game you could use a CheckIfOnGround() kind of function that would stop applying downward velocity when a object/character was colliding with a ground surface.

I would suggest that over applying opposite force when collision occurs. One issue that could arrive with that functionality would be if an entity collided on multiple objects. This would make the entity move upwards.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .