Home > DeveloperSection > Forums > Change texture on key down
Ankit Singh

Total Post:341

Points:2389
Posted on    December-12-2013 1:27 AM

 C# C# 
Ratings:


 1 Reply(s)
 978  View(s)
Rate this:

private void CheckKeyboardAndUpdateMovement()

{

    KeyboardState keyboardState = Keyboard.GetState();

    if (keyboardState.IsKeyUp(Keys.Left)) { ChangeTexture(1); }

    if (keyboardState.IsKeyUp(Keys.Right)) { ChangeTexture(2); }

    if (keyboardState.IsKeyDown(Keys.Left))

    {

        Movement -= Vector2.UnitX;

        ChangeTexture(3);

    }

    if (keyboardState.IsKeyDown(Keys.Right))

    {

        Movement += Vector2.UnitX;

        ChangeTexture(4);

    }

    if ((keyboardState.IsKeyDown(Keys.Space) || keyboardState.IsKeyDown(Keys.Up)) && IsOnFirmGround())

    {

        Movement = -Vector2.UnitY * JumpHeight;

    }

}

Here it is my method to get keyboard state and change texture based on which key is pressed.

it works if direction are pressed, but doesn't make its own job when nothing is pressed (just because both the IsKeyUp are true). Only the cases' order prevents the static texture to be shown while moving the sprite... My question is, how can I make a clean solution of this problem?



Pravesh Singh

Total Post:411

Points:2881
Posted on    December-12-2013 2:08 AM

Hi Ankit,
You can try this :

enum Direction { Left = 1, Right = 2}

Direction dir = Direction.Left; //or whatever

 

private void CheckKeyboardAndUpdateMovement()

{

    KeyboardState keyboardState = Keyboard.GetState();

    ChangeTexture((int)dir);

    if (keyboardState.IsKeyDown(Keys.Left))

    {

        Movement -= Vector2.UnitX;

        ChangeTexture(3);

        dir = Direction.Left;

    }

    if (keyboardState.IsKeyDown(Keys.Right))

    {

        Movement += Vector2.UnitX;

        ChangeTexture(4);

        dir = Direction.Right;

    }

    if ((keyboardState.IsKeyDown(Keys.Space) || keyboardState.IsKeyDown(Keys.Up)) && IsOnFirmGround())

    {

        Movement = -Vector2.UnitY * JumpHeight;

    }

}


Don't want to miss updates? Please click the below button!

Follow MindStick