【发布时间】:2014-12-03 18:12:20
【问题描述】:
我正在制作一个用于学习目的的 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 的 sprite sheet:
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;
}
}
在绘制方法中,我尝试检测精灵所面对的位置,我不确定最好的方法,但它不起作用,敌人被正确绘制和动画但有时沿地图朝向错误的方向路径并在某个点消失:
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);
}
}
}
【问题讨论】:
-
你还没有在这里真正问过问题;并且有很多代码(虽然总比没有代码好!)。你能缩小范围吗?根据给定的输入(提供实际/预期的输出)指出没有做你想做的事情的行/部分?
-
如果此代码与此问题相关,那么您似乎需要设计具有 FacingDirection 的角色的概念。似乎与此无关。设计完成后,您可以更新 Draw 方法以根据该数据操作图像/绘图。
-
我用代码上的一些 cmets 更新了问题以澄清。