简体   繁体   中英

C# XNA4.0 keyboardstate error

I am trying to move a sprite but it won't even let me debug. When i try to debug i get the following error:

Error 1 The name 'keys' does not exist in the current context

What am i doing wrong? or is it something else? According to multiple sources this is one of the ways to make a sprite move.

I've never been able to use keyboard input to move something or make something happen for some reason. Kinda lost here :(

Here's the code:

public class Game1 : Microsoft.Xna.Framework.Game
{
    Texture2D myTexture;
    Vector2 spritePosition = Vector2.Zero;
    Vector2 spriteSpeed = new Vector2(50.0f, 50.0f);
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    KeyboardState keystate;

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

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        myTexture = Content.Load<Texture2D>("sprite");
    }

    protected override void UnloadContent()
    {

    }

    protected override void Update(GameTime gameTime)
    {
        keystate = Keyboard.GetState();

        if (keystate.IsKeyDown(keys.right))
            spritePosition.X += spriteSpeed.X;
    }

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

        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
        spriteBatch.Draw(myTexture, spritePosition, Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}

Use the actual XNA Keys enumeration ( MSDN ):

protected override void Update(GameTime gameTime)
{
    keystate = Keyboard.GetState();

    if (keystate.IsKeyDown(Keys.Right))
        spritePosition.X += spriteSpeed.X;
}

Remember, C# is case sensitive!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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