protected virtual void CollisionDetection()
        if (CanGoRight() == false) pos.X -= velocity;

    protected bool IsTouchingLeft(Basic2d asset)
        return pos.X + dims.X / 2 > asset.pos.X &&
               pos.X - dims.X / 2 < asset.pos.X &&
               pos.Y + dims.Y / 2 < asset.pos.Y + dims.Y &&
               pos.Y - dims.Y / 2 > asset.pos.Y;

    protected bool CanGoRight()
        foreach (Basic2d asset in Globals.GameAssets)
            if (IsTouchingLeft(asset) == true) return false;
        return true;

That's my code(just starting) for collision detection. All of this code is in Character class which has also methods for moving and updating and displaying character.

I struggle with collision detection. I have all my assets(blocks) in the list of objects which is in the class named Globals. Class character is a subclass of a Basic2d class(this is class for all bricks assets).

So I check if a character is overlapping with any of bricks from the list. Criteria for checking left side overlapping is in the IsTouchingLeft method and it doesn't work. I cannot see what is wrong with this code, but every time I change sth it works differently but not well.

What should I change?

And the object of Character class has an origin point in in the center of the texture, but the object of Basic2d class has origin point in the bottom left corner.


1 Answer 1


Try the method below (just use hitLeft for your case):

public HitState checkHit(Rectangle r1, Rectangle r2)
   HitState retv;
    retv.hit = false;
    retv.hitTop = false;
    retv.hitBottom = false;
    retv.hitLeft = false;
    retv.hitRight = false;
    retv.hitInside = false;
    retv.hitExact = false;

    Rectangle temp1 = Rectangle.Intersect(r1, r2);
    if (temp1.Width == 0 && temp1.Height == 0)
        return retv;

    retv.hit = true;
    if (temp1.Y == r1.Y) retv.hitTop = true;
    if (temp1.Y+temp1.Height == r1.Y+r1.Height) retv.hitBottom = true;
    if (temp1.X == r1.X) retv.hitLeft = true;
    if (temp1.X+temp1.Width == r1.X+r1.Width) retv.hitRight = true;

    return retv;

public struct HitState
    public bool hit; // true if hit
    public bool hitTop; // true if hit top
    public bool hitBottom; // true if hit bottom 
    public bool hitLeft; // true if hit left
    public bool hitRight; // true if hit right
    public bool hitInside; // true if one inside other
    public bool hitExact; // only true if both bounding boxes exact size

You must log in to answer this question.

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