如何让这个球在中间而不是在侧面产卵? VisualStudio中的MonoGame

时间:2018-01-25 21:12:14

标签: visual-studio monogame

尝试创建一个简单的突破游戏,我已经编写了所有代码,除了我不明白为什么球在屏幕边界而不是在球拍(球员)的顶部。

Breakout game, ball on side

class Ball
{
    int Width => texture.Width;
    int Height => texture.Height;


    public Rectangle BoundingBox =>
        new Rectangle((int)position.X, (int)position.Y, Width, Height);

    Texture2D texture;
    Vector2 position;
    Vector2 speed;

    public void SetStartBallPosition(Rectangle rec)
    {

        position.X = rec.X + (rec.Width - Width);
        position.Y = rec.Y - Height;

        if (Game1.RandomNumber.Next(0, 2) < 1)
        {
            speed = new Vector2(-200.0f, -200.0f);
        }
        else
        {
            speed = new Vector2(200.0f, -200.0f);
        }


    }

    public void Draw(SpriteBatch sb)
    {
        sb.Draw(texture, position, Color.White);
    }

    public void Update(GameTime gt)
    {
        position += speed * (float)gt.ElapsedGameTime.TotalSeconds;

        if (position.X + Width > Game1.ScreenBounds.Width)
            speed.X *= -1;
            position.X = Game1.ScreenBounds.Width - Width;

        if (position.X < 0)
        {
            speed.X *= -1;
            position.Y = 0;
        }

        if (position.Y < 0)
        {
            speed.Y *= -1;
            position.Y = 0;
        }
    }

TL; DR

我的球在侧面而不是中间产生。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

SetStartBallPosition(Rectangle rec)中,您已将球位置设置在边界框的整个宽度上,减去球的整个宽度:

position.X = rec.X + (rec.Width - Width);

假设rec为空,那么为了获得中心,你需要将两个宽度分成两半。像这样:

position.X = rec.X + (rec.Width/2 - Width/2);

请注意,在划分时,他们不应该有小数。

让我知道它是否有效。