-1

那么我有这个代码:变量:

int x;
int maxX = 284;
//Rectangle
Rectangle sourceRect;
//Texture
Texture2D texture;

Update()方法中:

if (x++ >= maxX)
{
   x--; //To fix this x -= 284;
}

Draw()方法:

spriteBatch.Draw(texture, new Vector2(263 + x, 554), sourceRect, Color.White, 0f, origin, 1.0f, SpriteEffects.None, 0); //I have some properties which are not important 

所以我想要的是用这些整数水平移动字段,但它向右移动到从点 1 到点 2 并闪烁回到点 1 等等,这是所需的输出:

[        OUTPUT:        ]
[                       ]
[<1>FIELD            <2>]
[                       ]

所以该字段位于第 1 点。我希望它移动到第 2 点,如下所示:

[<1>FIELD---------------><2>]

然后,当它到达第 2 点时:

[<1><---------------FIELD<2>]

并像这样循环。从第 1 点到第 2 点,然后再到第 1 点和第 2 点。点之间的总距离为 284 像素(点是背景图像的一部分)。我知道这是关于递减整数,但怎么做呢?

4

3 回答 3

3

由于这是 XNA,您可以访问更新方法中的 GameTime 对象。有了这个和 Sin,你可以做你想做的非常简单的事情。

...
    protected override void Update(GameTime gameTime)
    {
        var halfMaxX = maxX / 2;
        var amplitude = halfMaxX; // how much it moves from side to side.
        var frequency = 10; // how fast it moves from side to side.
        x = halfMaxX + Math.Sin(gameTime.TotalGameTime.TotalSeconds * frequency) * amplitude;
    }
...

不需要分支逻辑来使某些东西从一边移动到另一边。希望能帮助到你。

于 2013-08-08T17:24:38.260 回答
2

我不太确定您要解释什么,但我认为您希望该点向右移动直到达到最大点,然后开始向左移动直到达到最小点。

一种解决方案是添加一个方向布尔值,例如

bool movingRight = true;
int minX = 263;

更新()

if( movingRight )
{
    if( x+1 > maxX )
    {
        movingRight = false;
        x--;
    }
    else
        x++;
}
else
{
    if( x-1 < minX )
    {
        movingRight = true;
        x++;
    }
    else
        x--;
}
于 2013-08-08T12:55:00.333 回答
1

您也可以使用运动因素,这样您就可以避免保持状态,当添加其他运动时,这种状态将变得更难维护。

 int speed = 1;

 void Update() { 
     x += speed;
     if (x < minX || x>MaxX) { speed =-speed; }
     x = (int) MathHelper.Clamp(x, minx, maxx);
 }
于 2013-08-08T14:07:41.837 回答