Jump to content

Diagonal Movement With Arrow Keys?


ceb
 Share

Recommended Posts

Set up a couple "ifs" in the update loop.

 

if( "PRESSING RIGHT ARROW" )

{

     "SPRITE".x += "MOVE AMOUNT"

}

else if( PRESSING LEFT ARROW)

{

     "SPRITE".x -= "MOVE AMOUNT"

}

 

if( "PRESSING DOWN ARROW" )

{

     "SPRITE".y += "MOVE AMOUNT"

}

else if( "PRESSING UP ARROW")

{

     "SPRITE".y -= "MOVE AMOUNT"

}

Link to comment
Share on other sites

Here is what my player movement code is:

var nothing = 'left';  if (cursors.left.isDown)    {        player.body.velocity.x = -230;        if (nothing != 'left')        {            player.animations.play('left');            nothing = 'left';        }    }    else if (cursors.right.isDown)    {        player.body.velocity.x = 230;        if (nothing != 'right')        {            player.animations.play('right');            nothing = 'right';        }    }	    else if (cursors.down.isDown)    {        player.body.velocity.y = 230;        if (nothing != 'down')        {            player.animations.play('down');            nothing = 'down';        }    }	   else if (cursors.up.isDown)    {        player.body.velocity.y = -230;        if (nothing != 'up')        {            player.animations.play('up');            nothing = 'up';        }    }    else    {        if (nothing != 'idle')        {            player.animations.stop();            if (nothing == 'left')            {                player.frame = 0;            }            nothing = 'idle';        }    }

And here is the demo ive got running http://justukfreebies.co.uk/games/, as you can see the player does not move diagonally when 2 keys left and up, or right and up are pressed. I was wondering if this was possible. 

Link to comment
Share on other sites

You have all the movement in one "if" you need to separate out the horizontal movement from the vertical movement.

 

if (cursors.left.isDown)
{

...

}

else if (cursors.right.isDown)
{

...

}

 

if (cursors.up.isDown)
{

...

}

else if (cursors.down.isDown)
{

...

}

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...