Right now I have a grid aligned solution in a method, probably not the most efficient, but it works.
if (this.hitbox.box.Intersects(o.hitbox.box) && (o.id != this.id))
{
intersect = Rectangle.Intersect(this.hitbox.box, o.hitbox.box);
float widthRatio = (float)intersect.Width / this.hitbox.box.Width;
float heightRatio = (float)intersect.Height / this.hitbox.box.Height;
if (widthRatio > heightRatio)
{
this.velocity = new Vector2(this.velocity.X, 0);
if (intersect.Center.Y < o.hitbox.absOrigin.Y)
{
UpdatePosition(new Vector2(this.position.X, this.position.Y - intersect.Height));
}
else if (intersect.Center.Y > o.hitbox.absOrigin.Y)
{
UpdatePosition(new Vector2(this.position.X, this.position.Y + intersect.Height));
}
}
else if (widthRatio < heightRatio)
{
this.velocity = new Vector2(0, this.velocity.Y);
if (intersect.Center.X < o.hitbox.absOrigin.X)
{
UpdatePosition(new Vector2(this.position.X - intersect.Width, this.position.Y));
}
else if (intersect.Center.X > o.hitbox.absOrigin.X)
{
UpdatePosition(new Vector2(this.position.X + intersect.Width, this.position.Y));
}
}
else if (widthRatio == heightRatio)
{
this.velocity = new Vector2(0, 0);
UpdatePosition(new Vector2(this.position.X - intersect.Width, this.position.Y - intersect.Height));
}
}
}
}
The Method UpdatePosition() updates the position of the rectangle of the sprite and the rectangle of the bounding box for the next Update().
Currently it only supports aligned rectangles, because it depends on the coordinate grid being aligned with the rectangles as well as the Rectangle struct not supporting rotation.
I would try to extend the Rectangle struct to include a rotation, but I have no idea how to do that.
I’ve heard there’s an extension library, I’m not sure if that might have my solution.
I’m pretty bad at vectors so I would appreciate any help. (Also why are rotated rectangles not built in?
)
