如何使用xna中的int在没有用户输入的情况下左右移动字段
本文关键字:输入 情况下 左右 字段 移动 用户 xna 何使用 中的 int | 更新日期: 2023-09-27 18:26:55
我有这样的代码:变量:
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
所以我想要的是用这些int水平移动字段,但它向右移动,从点1到点2,然后闪烁回到点1,依此类推,这是所需的输出:
[ OUTPUT: ]
[ ]
[<1>FIELD <2>]
[ ]
所以场在点1。我希望它移动到第2点,像这样:
[<1>FIELD---------------><2>]
然后,当它到达第2点时:
[<1><---------------FIELD<2>]
然后像这样循环。从点1到点2,然后再到点1和点2。点之间的总距离为284个像素(点是背景图像的一部分)。我知道这是关于整数的递减,但怎么做呢?
由于这是XNA,您可以访问更新方法中的GameTime对象。有了这个和罪恶,你可以做你想做的事,非常简单。
...
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;
}
...
不需要分支逻辑来使某些东西左右移动。希望能有所帮助。
我不太确定你想解释什么,但我认为你想让点向右移动,直到达到最大点,然后开始向左移动,直到到达最小点。
一种解决方案是添加方向布尔,例如
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--;
}
还可以使用移动因子,这样可以避免保持一种状态,当添加其他移动时,这种状态将变得更难维持。
int speed = 1;
void Update() {
x += speed;
if (x < minX || x>MaxX) { speed =-speed; }
x = (int) MathHelper.Clamp(x, minx, maxx);
}