0
\$\begingroup\$

I am making a 15 piece puzzle game and having difficulty making my sprite move one tile at a time, when i initially press the left key the sprite moves once, but after that the sprite moves multiple tiles after i press the keys again, instead of moving one tile like it should. Eventually this also messes with the sprites and some of them disappear. The code that i use to determine movement is:

if (positionx16 - positionx1 == 200 && positiony16 == positiony1)
{
    canswapleft1 = true;
}

if (oldState.IsKeyUp(Keys.Left) && newState.IsKeyDown(Keys.Left))
{
    if (positionx16 > 0 && canswapleft1 == true)
    {
        positionx16 += -widthoftile;
        positionx1 += widthoftile;
        canswapleft1 = false;
    }
}

The positionx16 is the X position of the player controlled tile, and the positionx1 referes to the X position of the 1st tile, this was repeated for each tile.

\$\endgroup\$

1 Answer 1

-1
\$\begingroup\$

if what you want is going somewhere once per key press, try this:

if (positionx16 - positionx1 == 200 && positiony16 == positiony1)
{
    canswapleft1 = true;
}

if (oldState.IsKeyUp(Keys.Left) && newState.IsKeyDown(Keys.Left))
{
    if (positionx16 > 0 && canswapleft1 == true)
    {
        positionx16 -= widthoftile; // use -= instead of += -x
        positionx1 += widthoftile;
        canswapleft1 = false;
        while(newState.IsKeyDown(Keys.Left))
        { // do Nothing
          // Just wait until release
          // but note that you wont be able to do anything else, even updating other 
          // stuff, so the player really needs to release the key.
        }
    }
}

this might not be efficient and can be not suitable for your game.

also i Don't see - on what you shared - that your oldState is set, do you have such a thing in your final code?

oldState = newState; // for example
\$\endgroup\$
2
  • \$\begingroup\$ It most probably is going to hang because while is not returning control to game framework. \$\endgroup\$ Commented Jun 17, 2020 at 0:21
  • \$\begingroup\$ This type of programming stuff works well on arduino so i was like ‘this could work’ but it might block the game for ever if the keyboard state is related to the update() funct but i don’t think it’s the case \$\endgroup\$ Commented Jun 17, 2020 at 0:55

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.