如何在没有用户输入的情况下,在xna中使用ints左右移动字段
我有这个密码: 变量:如何在没有用户输入的情况下,在xna中使用ints左右移动字段,xna,c#,Xna,C#,我有这个密码: 变量: int x; int maxX = 284; //Rectangle Rectangle sourceRect; //Texture Texture2D texture; 在Update()方法中: if (x++ >= maxX) { x--; //To fix this x -= 284; } spriteBatch.Draw(texture, new Vector2(263 + x, 554), sourceRect, Color.White, 0f
int x;
int maxX = 284;
//Rectangle
Rectangle sourceRect;
//Texture
Texture2D texture;
在Update()
方法中:
if (x++ >= maxX)
{
x--; //To fix this x -= 284;
}
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
以及Draw()
方法:
if (x++ >= maxX)
{
x--; //To fix this x -= 284;
}
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>]
[我不太清楚您想解释什么,但我认为您希望点向右移动,直到到达最大点,然后开始向左移动,直到到达最小点
一种解决方案是添加一个方向布尔,例如
bool movingRight = true;
int minX = 263;
更新()
if(向右移动)
{
如果(x+1>maxX)
{
movingRight=错误;
x--;
}
其他的
x++;
}
其他的
{
if(x-1
此外,您还可以使用移动因子,这样可以避免保持在添加其他移动时更难保持的状态
int speed = 1;
void Update() {
x += speed;
if (x < minX || x>MaxX) { speed =-speed; }
x = (int) MathHelper.Clamp(x, minx, maxx);
}
int速度=1;
无效更新(){
x+=速度;
如果(xMaxX){speed=-speed;}
x=(int)MathHelper.Clamp(x,minx,maxx);
}
由于这是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;
}
...
不需要分支逻辑使某些东西从一边移动到另一边。希望能有所帮助。我得到错误:“无法隐式地将类型“float”转换为“int”。”,但是,如果您编辑它使其对我有效,我将非常感谢。我添加了int cast,尽管您将停止使用float来控制速度;)