I am currently making an AWT game engine, a simple one just getting conversant with AWT. I am currently working on the physics of the game. I am trying to implement a function that moves the entity forward on it's direction from the north line, or the x axis. This is the code I am using to achieve this:
public void move(double d) {
oldX = x;
oldY = y;
double angle = Math.toRadians(getDirection());
int dx = (int) Math.round(Math.cos(angle) * d);
int dy = (int) Math.round(Math.sin(angle) * d);
setLocation(x + dx, y + dy);
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("direction = " + angle);
System.out.println("----------");
}
and I call this code in this snippet:
for(Entity e : entities) {
if(!e.getLevel().equals(this)) {
return;
}
e.move(3); //testing the code atm
e.changeDirection(e.getDirection() + 3);
}
The problem is that it won't go in a circle, or oval trajectory as I would expect when you have a vector forward (move(int i)
) method and changing the direction by 3 every tick as the force acting on the vector, or gravity if we were talking about Earth orbiting objects. This is the expected behaviour.
However, this is what actually happens:
Could you tell me why this behavior is occurring and how I could solve this? Thanks
The actual problem, as @harold says, is not the maths but the rendering. Here is what the fixed code to render the 2d entity looks like:
for(Entity e : entities) {
AffineTransform trans = new AffineTransform();
trans.setTransform(identity);
Point mouse = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointToScreen(mouse, this);
trans.rotate(Math.toRadians(e.getDirection()), e.getX(), e.getY());
//changed from trans.rotate(Me.getDirection(), e.getX() + e.image.getWidth(null)/2, e.getY() + e.image.getHeight(null)/2);
trans.translate(e.getX(), e.getY());
g2d.drawImage(e.getImage(), trans, this);
}