XNA - 水平移动动画矩形(无用户输入,但定时器)

时间:2013-08-07 17:25:00

标签: c# timer xna rectangles

在这里,我想在没有用户输入的情况下使用计时器移动这个动画矩形,也许?动画矩形应左右移动(从起点到终点,整个路径= 315像素)。我的意思是点1(从左侧开始)和点2(右侧结束)之间的315像素。 这是我的代码: 变量:

        //Sprite Texture
        Texture2D texture;
        //A Timer variable
        float timer = 0f;
        //The interval (300 milliseconds)
        float interval = 300f;
        //Current frame holder (start at 1)
        int currentFrame = 1;
        //Width of a single sprite image, not the whole Sprite Sheet
        int spriteWidth = 32;
        //Height of a single sprite image, not the whole Sprite Sheet
        int spriteHeight = 32;
        //A rectangle to store which 'frame' is currently being shown
        Rectangle sourceRect;
        //The centre of the current 'frame'
        Vector2 origin;

接下来,在LoadContent()方法中:

       //Texture load
       texture = Content.Load<Texture2D>("gameGraphics\\Enemies\\Sprite");

Update()方法:

    //Increase the timer by the number of milliseconds since update was last called
    timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
    //Check the timer is more than the chosen interval
    if (timer > interval)
    {
        //Show the next frame
        currentFrame++;
        //Reset the timer
        timer = 0f;
    }
    //If we are on the last frame, reset back to the one before the first frame (because currentframe++ is called next so the next frame will be 1!)
    currentFrame = currentFrame % 2;
    sourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);
    origin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);

最后,Draw()方法:

    //Texture Draw
    spriteBatch.Draw(texture, new Vector2(263, 554), sourceRect,Color.White, 0f, origin, 1.0f, SpriteEffects.None, 0);

所以我想移动sourceRect。 Ir必须左右循环。

1 个答案:

答案 0 :(得分:1)

您的spriteBatch.Draw()来电一直使用destinationRectangle的相同值。你想怎么搬家?例如,每帧的右边5个像素?只需将您的destinationRectangle(第二个参数更改为spriteBatch.Draw())更改为:

new Vector2(263 + (currentFrame * 5), 554);

编辑:评论请求的示例

class Foo
{
    int x;
    int maxX = 400;

    void Update(GameTime gameTime)
    {
        if (x++ >= maxX)
            x = 263;
    }

    void Draw()
    {
        spriteBatch.Draw(texture, new Vector2(263 + x, 554), sourceRect,Color.White, 0f, origin, 1.0f, SpriteEffects.None, 0);
    }
}

当然,除了spriteBatch.Draw()调用之外,您将保留所有当前代码;你只需添加x部分。