So, I have this Panel class. This is a bit like a window where you can resize, close, add buttons, sliders, etc. Very similar to the status screen in Morrowind, if any of you remember. The behavior I want is that when the sprite is outside the borders of the panel, it cannot be drawn, and if it partially extends beyond only the part inside that is drawn. So now he makes a rectangle representing the borders of the panel and a rectangle for the sprite, he finds the intersection rectangle between the two, and then translates this intersection into the local coordinates of the sprite rectangle and uses this for the original rectangle. It works and is as smart as I feel that the code I cannot shake the feeling that there is a better way to do this. Besides,with this setting, I can’t use the global transformation matrix for my 2D camera, everything in the “world” must be passed by the camera argument for drawing. Anyway, here is the code I have:
to cross:
public static Rectangle? Intersection(Rectangle rectangle1, Rectangle rectangle2)
{
if (rectangle1.Intersects(rectangle2))
{
if (rectangle1.Contains(rectangle2))
{
return rectangle2;
}
else if (rectangle2.Contains(rectangle1))
{
return rectangle1;
}
else
{
int x = Math.Max(rectangle1.Left, rectangle2.Left);
int y = Math.Max(rectangle1.Top, rectangle2.Top);
int height = Math.Min(rectangle1.Bottom, rectangle2.Bottom) - Math.Max(rectangle1.Top, rectangle2.Top);
int width = Math.Min(rectangle1.Right, rectangle2.Right) - Math.Max(rectangle1.Left, rectangle2.Left);
return new Rectangle(x, y, width, height);
}
}
else
{
return null;
}
}
and for the actual drawing on the panel:
public void DrawOnPanel(IDraw sprite, SpriteBatch spriteBatch)
{
Rectangle panelRectangle = new Rectangle(
(int)_position.X,
(int)_position.Y,
_width,
_height);
Rectangle drawRectangle = new Rectangle();
drawRectangle.X = (int)sprite.Position.X;
drawRectangle.Y = (int)sprite.Position.Y;
drawRectangle.Width = sprite.Width;
drawRectangle.Height = sprite.Height;
if (panelRectangle.Contains(drawRectangle))
{
sprite.Draw(
spriteBatch,
drawRectangle,
null);
}
else if (Intersection(panelRectangle, drawRectangle) == null)
{
return;
}
else if (Intersection(panelRectangle, drawRectangle).HasValue)
{
Rectangle intersection = Intersection(panelRectangle, drawRectangle).Value;
if (Intersection(panelRectangle, drawRectangle) == drawRectangle)
{
sprite.Draw(spriteBatch, intersection, intersection);
}
else
{
sprite.Draw(
spriteBatch,
intersection,
new Rectangle(
intersection.X - drawRectangle.X,
intersection.Y - drawRectangle.Y,
intersection.Width,
intersection.Height));
}
}
}
So, I think my question is, is there a better way to do this?
Update: I just found out about the ScissorRectangle property. It seems like a decent way to do it; it requires that the RasterizerState object be created and passed to spritebatch.Begin overload, which accepts it. Seems like this might be the best solution. There is also a Vidoport, which I can change. Thoughts? :)