Why does my sprite not move

时间:2015-11-12 18:45:39

标签: c# class methods xna monogame

Im trying to make a simple Pong game using classes for the first time, but after following some tutorial to the letter, my code is not working. Even though I do have everything the exact same. Could anyone help me by taking a look at it? The Child Class Ball Update() is supposed to make a Ball move on screen when I press left/right. There are no errors but the ball wont move.

The Class Code:

public class Sprite
{
    public Texture2D Texture;
    public Rectangle Hitbox;

    public KeyboardState KBS = Keyboard.GetState();
    public virtual void Update()
    {

    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(Texture, Hitbox, Color.White);
    }
}

public class Ball : Sprite
{
    public Ball(Texture2D newTexture, Rectangle newHitbox)
    {
        Texture = newTexture;
        Hitbox = newHitbox;
    }

    public override void Update()
    {
        if(KBS.IsKeyDown(Keys.Right))
        {
            Hitbox.X += 3;
        }
        if (KBS.IsKeyDown(Keys.Left))
        {
            Hitbox.X -= 3;
        }
    }
}

The Main Code:

public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    //Gameworld
    Ball Ball;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        Ball = new Ball(Content.Load<Texture2D>("Ball"), new Rectangle(0, 0, 24, 24));
    }

    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        Ball.Update();
        base.Update(gameTime);
    }

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

        spriteBatch.Begin();
        Ball.Draw(spriteBatch);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

So if anyone could help me out I'd be Grateful!

1 个答案:

答案 0 :(得分:0)

您必须在每个更新周期更新键盘的状态。

将它添加到您的Sprite类,并从Game1调用它。

public void Update(GameTime gameTime)
{
     KBS = Keyboard.GetState();
}