So I’m working on a 2D game right now, and I am working on WASD movement. When I am moving, it seems to work fine, but then the sprite rendered by the updated coordinates just either goes in circles or turns and changes direction, and I need to know if somebody can shed some light on the issue. If you need more code posted, just ask :).
Is there something I am missing in my calculations or how the translations are handled?
Method that gets the rotation from the mouse and position
[icode]
/**
* Calculate the rotation for the character
*/
public float getZRotation(Rectangle mouse, Vector character){
return (float) Math.toDegrees(Math.atan2(mouse.x - character.getX(), mouse.y - character.getY()));
}
[/icode]
Method that handles movement (I just do handleMovement(0.5f) every frame). The Vector object just stores and x and y.
[icode]
/**
* Handle movement for the player
*/
public void handleMovement(float speed){
// get the angle
Vector position = DisplayManager.getInstance().getRenderer().getCamera().getPosition();
// gets the current position of the camera / player
Rectangle mouse = DisplayManager.getInstance().getRenderer().getMouse();
// gets the current location of the mouse and the rectangle representing it.
float rotation = getZRotation(mouse, position);
// handle the coordinates
Keyboard.poll();
float x = 0.0f;
float y = 0.0f;
if (Keyboard.isKeyDown(Keyboard.KEY_W)) {
y += (float)(Math.sin(Math.toRadians(rotation)) * speed);
x += (float)(Math.cos(Math.toRadians(rotation)) * speed);
}
else if (Keyboard.isKeyDown(Keyboard.KEY_S)) {
y -= (float)(Math.sin(Math.toRadians(rotation)) * speed);
x -= (float)(Math.cos(Math.toRadians(rotation)) * speed);
}
// flip sine and cosine to be perpendicular.
else if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
y -= (float)(Math.sin(Math.toRadians(90.0f - rotation)) * speed);
x -= (float)(Math.cos(Math.toRadians(90.0f - rotation)) * speed);
}
else if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
y += (float)(Math.sin(Math.toRadians(90.0f - rotation)) * speed);
x += (float)(Math.cos(Math.toRadians(90.0f - rotation)) * speed);
}
y /= -1; // flip the y
// change movement. This adds to the camera's last position.
camera.addToPosition(x, y);
}
[/icode]