我正在爲學習目的製作2D塔防遊戲,現在我陷入瞭如何讓移動中的敵人看向正確的方向。如何檢測精靈在哪個方向移動?
這是我嘗試沒有成功:
// Class constructor
public AnimatedSprite(Texture2D texture, int lines, int columns, Vector2 position)
: base (texture, position)
{
this.texture = texture;
this.position = position;
Lines = lines; // How many lines the sprite-sheet have
Columns = columns; How many columns the sprite-sheet have
totalFrames = Lines * Columns;
}
這裏的更新方法,它是一個5x4的精靈表:
public override void Update(GameTime gameTime)
{
// Depending on the direction the sprite is moving
// it will use different parts of the sprite-sheet
if (west == true)
{
initialFrame = 0;
finalFrame = 4;
}
if (east == true)
{
initialFrame = 5;
finalFrame = 9;
}
if (north == true)
{
initialFrame = 10;
finalFrame = 14;
}
if (south == true)
{
initialFrame = 15;
finalFrame = 19;
}
// When to update the current frame
timeSinseLastFrame += gameTime.ElapsedGameTime.Milliseconds;
if (timeSinceLastFrame > milisecondsPerFrame)
{
timeSinceLastFrame -= milisecondsPerFrame;
currentFrame++;
// Reset the frame to complete the loop
if (currentFrame == finalFrame)
currentFrame = initialFrame;
}
}
在Draw方法我試圖偵測精靈所面臨的位置,我不確定最好的辦法,但它不工作,敵人繪製正確和動畫,但有時沿着地圖路徑面對錯誤的方向,並在某一點他們消失:
public override void Draw(SpriteBatch spriteBatch)
{
int width = texture.Width/Columns;
int height = texture.Height/Lines;
int line = (int)((float)currentFrame/(float)Columns);
int column = currentFrame % Columns;
Rectangle originRectangle = new Rectangle(width * column, height * line, width, height);
Rectangle destinationRectangle = new Rectangle((int)position.X, (int)position.Y, width, height);
// Heres what i think it's not correct, how to detect the direction
// I tried to calculate it by the last X and Y position
// So if the current Y value is smaller the last Y value
// The sprite moved south
Rectangle lastPosition = originRectangle;
Rectangle destinationPosition = destinationRectangle;
if (lastPosition.Y < destinationPosition.Y)
{
north = true;
south = false;
east = false;
west = false;
}
if (destinationRectangle.Y > lastPosition.Y)
{
north = false;
south = true;
east = false;
west = false;
}
if (destinationRectangle.X > lastPosition.X)
{
north = false;
south = false;
east = true;
west = false;
}
if (destinationRectangle.X < lastPosition.X)
{
north = false;
south = false;
east = false;
west = true;
}
spriteBatch.Draw(texture, destinationRectangle, originRectangle, Color.White);
}
}
}
你還沒有真正問了一個問題在這裏;並且有很多代碼(比沒有代碼好!)。你能縮小一切嗎?根據給定的輸入指出沒有做到你想要的行/部分(提供實際/預期的輸出)? – BradleyDotNET 2014-12-03 18:18:29
如果此代碼是與此問題相關的所有內容,那麼您似乎需要設計具有FacingDirection的角色概念。似乎沒有任何關係。一旦你設計好了,你可以更新Draw方法來根據這些數據來操作圖像/繪圖。 – 2014-12-03 18:54:11
我更新了這個問題,並在代碼上加了幾條評論來澄清。 – ViNi 2014-12-03 19:35:22