问题是你有多个批次,定义为spriteBatch.Begin()和spriteBatch.End()之间的代码。
默认情况下,spriteBatch.Begin() 不带参数调用,所有精灵都按照调用顺序绘制:第一个绘制调用是背景。第二个draw call将在第一个之上...
正如@ProfessionalKent 在他的回答中所说,使用layerDepth 参数:
spriteBatch.Draw(Texture, destinationRectangle, sourceRectangle, Color.White, 0.0f, Vector2.Zero, SpriteEffects.None, layerDepth);
layerDepth 接受任何 float 值(默认为 0),较低的值呈现在较高的值之上。任何相同的值都按输入的顺序完成。
此参数也适用于spriteBatch.DrawString()
但是,layerDepth 仅在同一批次中有效。一旦调用 End(),批次就会被排序、展平并呈现到帧缓冲区。
解决方案
写下所有绘制对象所需的深度。替换以下代码中的layerDepth 数字以反映您的分析。
删除整个项目中的所有 spriteBatch.Begin() 和 spriteBatch.End() 行。除非spriteBatch.Begin() 没有default(第81 和91-100 行)参数。
在Game1.csGraphicsDevice.Clear之后尽早打开spriteBatch:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
// Your existing code here.
spriteBatch.End();
//oprozniony, nothing should be here
}
在 GameScene.cs 中:
private void DrawGame()
{
// The ,, is for the null source rectangle,
spriteBatch.Draw(floor1, rec_floor1,, color1, 0.0f, Vector2.Zero, SpriteEffects.None, 2);
spriteBatch.Draw(floor2, rec_floor2,, color1, 0.0f, Vector2.Zero, SpriteEffects.None, 3);
spriteBatch.Draw(house1, rec_house1,,color1, 0.0f, Vector2.Zero, SpriteEffects.None, 1);
// example of a table the animatedSprite(at a depth of 0) will walk or move behind(note the negative depth):
// spriteBatch.Draw(stol, rec_stol, , color1, 0.0f , Vector2.Zero, SpriteEffects.None, -1);
}
在 AnimatedSprite.cs 中
public void Draw(SpriteBatch spriteBatch, Vector2 location)
{
// unless the width and height can change when the game is running, they should be class variables set in the constructor
int width = Texture.Width / Columns;
int height = Texture.Height / Rows;
// removed unnecessary casts:(unless currentFrame is not an int)
int row = currentFrame / Columns;
int column = currentFrame % Columns;
Rectangle sourceRectangle = new Rectangle(width * column, height * row, width, height);
Rectangle destinationRectangle = new Rectangle((int)location.X, (int)location.Y, 120, 140);
if (Game1.przelacznik_w_bezruchu == true) sourceRectangle = new Rectangle(0, 0, width, height);
// Place the sprite at Depth of 0.
spriteBatch.Draw(Texture, destinationRectangle, sourceRectangle, Color.White, 0.0f, Vector2.Zero, SpriteEffects.None, 0);
}
有些情况需要多个批次。如果是这种情况,请手动按深度顺序拆分批次。