Car Game - Handling movement
Hello, (Yes I joined this forum so I could ask questions, sorry guys)
I am currently making a car based java game and was wondering how to handle movements? It is topdown and I am not sure exactly how to do it.
Currently I have acceleration and angle [as doubles], W is accelerate, S is break (slows the acceleration and if held when you have no acceleration you go back slowly [reverse]) and D/A changes angles.
How can I make it so based on the angle, he moves relative to the screen? Say if you hold W you move down the Y axis, but pressing the A key makes you move both up the X axis and down the Y axis. So the car goes to the bottom right of the screen?
This is what I currently have, its pretty fail I have just been testing things out and I know it doesn't work and I know why, I just don't know how to make it awesome.
Code:
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_W)
{
accelerate = true;
}
else if (e.getKeyCode() == KeyEvent.VK_S)
{
brake = true;
}
else if (e.getKeyCode() == KeyEvent.VK_A)
{
turnLeft = true;
}
else if (e.getKeyCode() == KeyEvent.VK_D)
{
turnRight = true;
}
}
@Override
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_W)
{
accelerate = false;
}
else if (e.getKeyCode() == KeyEvent.VK_S)
{
brake = false;
}
else if (e.getKeyCode() == KeyEvent.VK_A)
{
turnLeft = false;
}
else if (e.getKeyCode() == KeyEvent.VK_D)
{
turnRight = false;
}
}
@Override
public void keyTyped(KeyEvent e)
{
// TODO Auto-generated method stub
}
@Override
void draw(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle car = new Rectangle((int) x,(int) y,10,10);
g2.draw(car);
}
@Override
void step()
{
if (accelerate)
{
acceleration += 1.5;
}
else if (brake)
{
acceleration -= 0.5;
}
if (angle == 3)
{
yVel = acceleration;
xVel = 0.0;
}
else if (angle == 5)
{
yVel = 0.0;
xVel = acceleration;
}
else if (angle == 1)
{
xVel = -acceleration;
yVel = 0.0;
}
x += xVel;
y += yVel;