0

Using visual studio 2015 I use a picture box as a player and have it move up, down, left and right. When the picture box moves it shrinks and then looks like it teleports. That is not what it is supposed to do. How do I properly get the picture box to change whenever I press the wasd keys?

if (e.KeyCode == Keys.D)
{
    x += 6;
    playerBox.Image = Properties.Resources.playerRight;
}

//moves player right and changes the image

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
no name
  • 23
  • 3

1 Answers1

-1

Just add to / subtract, the picturebox Top and Left:

if (e.KeyCode == Keys.D)
{
    playerBox.Left += 6;
    playerBox.Image = Properties.Resources.playerRight;
}

also to avoid changing photo everytime if the direction has not changed you may do something like this:

if (e.KeyCode == Keys.D)
{
    playerBox.Left += 6;
    if((Keys)playerBox.Tag!=e.KeyCode)
    playerBox.Image = Properties.Resources.playerRight;
}

You must of course set some inital value for playerBox.Tag or you will get an error as it cant be cast to Keys

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • I ran it in visual studio and it moves a little then goes right back to its starting position. These are the variables I use in my form- int x = playerBox.Location.X; int y = playerBox.Location.Y; – no name Feb 01 '19 at 22:13
  • its hard to say what is exatly wrong as you haven't shared the whole code, but obviously, somewhere you are assigning old values to x and y. but why don't you use Left and Top? – Ashkan Mobayen Khiabani Feb 01 '19 at 22:15
  • Ok thanks I changed it and it moves correctly but the image still shrinks when I hold the key down. Thanks for your help – no name Feb 01 '19 at 22:45