Привет, stackoverflow!Текстура остается на месте во время движения игрока
Я работаю над приключенческой игрой 2D-прокруткой на C# с использованием MonoGame, и я столкнулся с особой проблемой.
Вкратце: экземпляр Player присвоил текстуру 2D, содержащую текстуру игрока (в этом примере синяя коробка с зеленой рамкой 2px) Когда игрок перемещается, текстура «остается на месте», и игрок постепенно становится зеленым, когда он покидает где текстура. Это, конечно, не должно происходить, поскольку текстура должна быть перерисована в точном месте игрока каждый раз, когда вызывается Draw().
Другими словами, игроку все равно должен быть синий ящик с зеленой рамкой 2px, где бы он ни двигался.
изображений для лучшей иллюстрации:
исходное состояние
Игрок перемещается вниз, оставляя текстуру позади.
Пока он не будет полностью зеленым.
И когда он возвращается к своей первоначальной позиции, правильная текстура начинает показывать снова
Я сократить код, чтобы это голые кости, но проблема все еще сохраняется.
Game.cs не содержит ничего интересного, инициализацию игрока и Draw метод здесь:
//inside of Initialize()
player = new Player(GraphicsDevice, Vector2.Zero);
protected override void Draw(GameTime gameTime) {
GraphicsDevice.Clear(Color.CornflowerBlue);
levelSpriteBatch.Begin();
player.Draw(gameTime, levelSpriteBatch);
levelSpriteBatch.End();
base.Draw(gameTime);
}
Player.cs (весь файл) здесь:
class Player {
public Vector2 Position
{
get { return position; }
}
Vector2 position;
public Texture2D Texture { get; private set; }
public const int Width = 32;
public const int Height = 32;
// Input configuration
private const Keys leftButton = Keys.A;
private const Keys rightButton = Keys.D;
private const Keys upButton = Keys.W;
private const Keys downButton = Keys.S;
//Current state
private float LRmovement;
private float UDmovement;
public Player(GraphicsDevice graphicsDevice, Vector2 position) {
this.position = position;
CreateTexture(graphicsDevice, Width, Height);
}
public void Update(GameTime gameTime, KeyboardState keyboardState) {
GetInput(keyboardState);
position.X += LRmovement;
position.Y += UDmovement;
LRmovement = 0.0f;
UDmovement = 0.0f;
}
private void CreateTexture(GraphicsDevice graphicsDevice, int width, int height) {
Texture = new Texture2D(graphicsDevice, width, height);
GraphicsHelper.FillRectangle(Texture, Color.Red);
GraphicsHelper.OutlineRectangle(Texture, Color.Green, 2);
}
private void GetInput(KeyboardState keyboardState) {
LRmovement = 0;
UDmovement = 0;
if (Math.Abs(LRmovement) < 0.5f)
LRmovement = 0.0f;
if (Math.Abs(UDmovement) < 0.5f)
UDmovement = 0.0f;
if (keyboardState.IsKeyDown(leftButton))
LRmovement = -1.0f;
else if (keyboardState.IsKeyDown(rightButton))
LRmovement = 1.0f;
if (keyboardState.IsKeyDown(upButton))
UDmovement = -1.0f;
else if (keyboardState.IsKeyDown(downButton))
UDmovement = 1.0f;
}
public void Draw(GameTime gameTime, SpriteBatch spriteBatch) {
spriteBatch.Draw(Texture, position, new Rectangle((int)Position.X, (int)Position.Y, Width, Height), Color.White);
}
}
И GraphicsHelper.cs:
class GraphicsHelper {
public static void FillRectangle(Texture2D texture, Color fill) {
Color[] color = new Color[texture.Width * texture.Height];
texture.GetData(color);
for (int i = 0; i < texture.Width * texture.Height; ++i)
color[i] = fill;
texture.SetData(color);
}
public static void OutlineRectangle(Texture2D texture, Color outline, int outlineWidth) {
Color[] color = new Color[texture.Width * texture.Height];
texture.GetData(color);
int index = 0;
for (int y = 0; y < texture.Height; ++y) {
for (int x = 0; x < texture.Width; ++x) {
if (y < outlineWidth || x < outlineWidth || y > texture.Height - outlineWidth || x > texture.Width - outlineWidth)
color[index] = outline;
++index;
}
}
texture.SetData(color);
}
}
Это ВСЕ КОД. Я честно из идей.