繁体   English   中英

如何在Xna中使用int在没有用户输入的情况下左右移动字段

[英]How to move a field left and right without user input, using ints in xna

我有以下代码:变量:

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像素(点是背景图像的一部分)。 我知道这是关于减少整数,但是该怎么做呢?

由于这是XNA,因此您可以在更新方法中访问GameTime对象。 有了Sin和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;
    }
...

无需分支逻辑即可使某些事物从一侧移到另一侧。 希望能帮助到你。

我不太确定您要解释什么,但我想您要使该点向右移动直到达到最高点,然后再开始向左移动直到达到最低点。

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

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);
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM