Hi there, I'm trying to code a simple program whereby an object (in this case a boat) can move freely around the screen via the use of the arrow keys. Now the left and right arrows should change the angle the boat faces, while the up arrow makes the boat move in the direction the boat faces, while the back arrow, you've guessed it, makes the boat reverse.
Now so far I have been able to make the boat rotate by 22.5 degrees in both directions using the left and right arrows by using transform.
The applet I have allows me to move forward and backwards too, but not in the way I need it, for example sometimes it changes up to down, or goes in the wrong direction altogether.
I was hoping someone here could please review the code I will add at the bottom, and tell me where I'm going wrong with this. Thank you.
Here is my KeyPressed code:
public void keyPressed(KeyEvent event){
switch (event.getKeyCode()){
case KeyEvent.VK_UP:
//forward movement
// work out horizontal and vertical components of the speed
hspeed = ((double)boatSpeed) * Math.cos(currentAngle);
vspeed = ((double)boatSpeed) * Math.sin(currentAngle);
// move the actual boats here
xpos = xpos + (int) hspeed;
ypos = ypos + (int) vspeed;
break;
case KeyEvent.VK_DOWN:
// work out horizontal and vertical components of the speed
hspeed = ((double)boatSpeed) * Math.cos(currentAngle);
vspeed = ((double)boatSpeed) * Math.sin(currentAngle);
// move the actual boats here
xpos = xpos - (int) hspeed;
ypos = ypos - (int) vspeed;
break;
case KeyEvent.VK_LEFT:
//rotates image 22.5 degrees
currentAngle -=22.5;
break;
case KeyEvent.VK_RIGHT:
//rotates image 22.5 degrees
currentAngle +=22.5;
break;
}
//repaints image after each move
repaint();
}