Actually i'm watching a tutorial series on youtube about 2D Game programming in Java. My question is about the player-movement.
The first version:
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT) {
player.setX(p.getX() + 5);
}else if(key == KeyEvent.VK_LEFT) {
player.setX(p.getX() - 5);
}else if(key == KeyEvent.VK_DOWN) {
player.setY(p.getY() + 5);
}else if(key == KeyEvent.VK_UP) {
player.setY(p.getY() - 5);
}
}
The problem in this first version is, that if you press now for example VK-RIGHT (and holding it), than the figur in the game moves first one step to the right, then stops for a half second or so and then the figur moves constantly to the right. The problem here is the stopping, which takes a half second or so. This is not smooth.
Then the author of the tutorial presented a second, better version:
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT) {
player.setVelX(5);
}else if(key == KeyEvent.VK_LEFT) {
player.setVelX(-5);
}else if(key == KeyEvent.VK_DOWN) {
player.setVelY(5);
}else if(key == KeyEvent.VK_UP) {
player.setVelY(-5);
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT) {
player.setVelX(0);
}else if(key == KeyEvent.VK_LEFT) {
player.setVelX(0);
}else if(key == KeyEvent.VK_DOWN) {
player.setVelY(0);
}else if(key == KeyEvent.VK_UP) {
player.setVelY(0);
}
}
and the tick() method in the Player.java:
public void tick() {
x += velX;
y += velY;
}
The author said, that the second version is smoother, because we don't need to ask first with the get-methods the actually value of x/y. Is this really the reason, why the second method is smoother respectively we don't have still this stop for a half second or so?
If this is really the reason, why the start time of the player figur is in both version the same? In the first version the player figure would then have to need more time to start movement? But this is not the case! The difference is this stop for a half second or so after the first steop of movement is finished.