Reputation: 1088
I have a class for my sprites like so:
public class Sprite : System.ICloneable
{
public Image SpriteImage { get; private set; }
public Image SpriteMask { get; private set; }
public Sprite(Image img, Image maskImg = null)
{
this.SetImage(img, maskImg);
}
public void SetImage(Image img, Image maskImg = null)
{
this.SpriteImage = new Bitmap(img,img.Width,img.Height);
if (maskImg != null)
{
this.SpriteMask = new Bitmap(maskImg, maskImg.Width, maskImg.Height);
}
else
{
this.SpriteMask = this.SpriteImage;
}
}
public virtual object Clone()
{
return new Sprite(this.SpriteImage,this.SpriteMask);
}
public void FlipHorizontally()
{
this.SpriteImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
this.SpriteMask.RotateFlip(RotateFlipType.RotateNoneFlipX);
}
public void FlipVertically()
{
this.SpriteImage.RotateFlip(RotateFlipType.RotateNoneFlipY);
this.SpriteMask.RotateFlip(RotateFlipType.RotateNoneFlipY);
}
}
since I have SpriteMask and SpriteImage I created a function to rotate them both without hassle. In another class I have:
public void ChangeDirection(bool facingRight)
{
if (facingRight != this.FacingRight)
{
for(int i = 0; i < this.Sprites.Count; i++)
{
this.Sprites[i].FlipHorizontally();
}
foreach (Weapon weapon in this.CollectedWeapons)
{
weapon.ChangeDirection(facingRight);
}
this.FacingRight = facingRight;
}
}
this.Sprites is List<Sprite> Sprites;
. Now when this code is ran, the sprites to not flip, but if I change sprite.FlipHorizontally
to this.Sprites[i].SpriteImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
it works fine. Why is this?
Upvotes: 2
Views: 1018
Reputation: 31393
In your Sprite
constructor you allow the sprite mask argument to be null. If it is null, look at what you do :
if (maskImg != null)
{
this.SpriteMask = new Bitmap(maskImg, maskImg.Width, maskImg.Height);
}
else
{
this.SpriteMask = this.SpriteImage;
}
You set SpriteMask
to SpriteImage
- since an image is a reference type you are only assigning the reference. There is still only one Image
object but both variables are pointing to it. When you call :
public void FlipHorizontally()
{
this.SpriteImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
this.SpriteMask.RotateFlip(RotateFlipType.RotateNoneFlipX);
}
...since SpriteImage
and SpriteMask
are the same object, you are flipping the image and then flipping it back again. What you might consider is making a copy of the sprite image for the mask if the mask is not provided :
if (maskImg != null)
{
this.SpriteMask = new Bitmap(maskImg, maskImg.Width, maskImg.Height);
}
else
{
this.SpriteMask = new Bitmap(this.SpriteImage);
}
Upvotes: 1