我的精灵课程是这样的:
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);
}
}
因为我有SpriteMask和SpriteImage,所以我创建了一个旋转它们的函数,没有麻烦。在另一堂课中我有:
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是List<Sprite> Sprites;
。现在,当这段代码运行时,精灵不会翻转,但如果我将sprite.FlipHorizontally
更改为this.Sprites[i].SpriteImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
,它就能正常工作。这是为什么?
答案 0 :(得分:1)
在Sprite
构造函数中,您允许sprite mask参数为null。如果它为null,请查看您的操作:
if (maskImg != null)
{
this.SpriteMask = new Bitmap(maskImg, maskImg.Width, maskImg.Height);
}
else
{
this.SpriteMask = this.SpriteImage;
}
您将SpriteMask
设置为SpriteImage
- 因为图片是参考类型,您只需指定参考。仍然只有一个Image
对象,但两个变量都指向它。当你打电话:
public void FlipHorizontally()
{
this.SpriteImage.RotateFlip(RotateFlipType.RotateNoneFlipX);
this.SpriteMask.RotateFlip(RotateFlipType.RotateNoneFlipX);
}
...由于SpriteImage
和SpriteMask
是同一个对象,您正在翻转图像,然后再将其翻转回来。如果未提供掩码,您可以考虑为掩码制作精灵图像的副本:
if (maskImg != null)
{
this.SpriteMask = new Bitmap(maskImg, maskImg.Width, maskImg.Height);
}
else
{
this.SpriteMask = new Bitmap(this.SpriteImage);
}