如何修复我的平台碰撞检测?

时间:2015-08-30 17:52:50

标签: c# xna

我正在制作一款允许我的2D精灵在平台上跳跃的游戏,但是当它落在平台上时,我的2D精灵并不完全位于平台的顶部,有时它的位置超出或相同该平台。

//here is my code:

Texture2D jumper;
Texture2D tile;
Vector2 position, velocity;
Rectangle top;
Rectangle tile_rectangle;
Rectangle jumper_rectangle;
KeyboardState ks;

bool jump;

//here is my Load Content:

protected override void LoadContent()
{
    jump = true;
    position.X = 10;
    position.Y = 10;

    jumper = Content.Load<Texture2D>("character");
    tile = Content.Load<Texture2D>("tile");

    tile_rectangle = new Rectangle(300, 350, tile.Width, tile.Height);
    top = new Rectangle(tile_rectangle.X, tile_rectangle.Y - 16, tile_rectangle.Width, 10);
}

//Here is my update:

protected override void Update(GameTime gameTime)
{
    ks = Keyboard.GetState();
    position += velocity;

    float i = 1;

    if (ks.IsKeyDown(Keys.Up) && jump == false)
    {
        position.Y -= 10f;
        velocity.Y = -25f;
        jump = true;
    }

    if (jump == true)
    {

        velocity.Y += 2f * i;
    }

    if (position.Y > 400)
    {

        jump = false;
    }

    if (jump == false)
    {
        velocity.Y = 0f;
    }

    BoundingBox();

    if (ks.IsKeyDown(Keys.Right))
    {
        position.X += 5f;
        velocity.X = +0.05f;

        if (jumper_rectangle.Left > tile_rectangle.Right)
        {
            jump = true;
        }
    }

    if (ks.IsKeyDown(Keys.Left))
    {
        position.X -= 5f;
        velocity.X = -0.05f;

        if (jumper_rectangle.Right < tile_rectangle.Left)
        {
            jump = true;
        }
    }
    jumper_rectangle = new Rectangle((int)position.X, (int)position.Y, jumper.Width, jumper.Height);
    BoundingBox();
    base.Update(gameTime);

}

//here is my draw:

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    spriteBatch.Begin();
    spriteBatch.Draw(jumper, jumper_rectangle, Color.White);
    spriteBatch.Draw(tile, tile_rectangle, Color.White);
    spriteBatch.End();

    base.Draw(gameTime);
}

//here is my method on landing:

public void BoundingBox()
{
    if (jumper_rectangle.Intersects(top))
    {
        if (jumper_rectangle.Bottom > top.Top)
        {
            position.Y--;
            jump = false;
        }
    }
}

我哪里出错或是否有其他方式?

0 个答案:

没有答案