Reputation: 51
Just for fun I thought I would create the game Asteroids. I'm a little bit stuck on the the fact I can't get the player to always look where the mouse is. Here is the player class below.
public class Player extends GameObject {
private int size;
public Player(float x, float y, int width, int height) {
super(x, y, width, height);
size = width / 2 + height / 2;
}
public void update() {
}
public void render(Graphics g) {
Point mouse = MouseInfo.getPointerInfo().getLocation();
int centerX = (int) (mouse.getX() - getX());
int centerY = (int) (mouse.getY() - getY());
double angle = Math.toDegrees(Math.atan2(centerY, centerX));
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.white);
g2d.rotate(angle, (int) getX() + getWidth() / 2, (int) getY() + getHeight() / 2);
g2d.drawLine((int) getX() + getWidth() / 2, (int) getY(), (int) getX(), (int) getY() + getHeight());
g2d.drawLine((int) getX() + getWidth() / 2, (int) getY(), (int) getX() + getWidth(), (int) getY() + getHeight());
g2d.drawLine((int) getX(), (int) getY() + getHeight(), (int) getX() + getWidth() / 2, (int) getY() + getHeight() - size / 6);
g2d.drawLine((int) getX() + getWidth(), (int) getY() + getHeight(), (int) getX() + getWidth() / 2, (int) getY() + getHeight() - size / 6);
}
public Rectangle getBounds() {
return new Rectangle((int) getX(), (int) getY(), getWidth(), getHeight());
}
public void setSize(int size) {
this.size = size;
}
public int getSize() {
return size;
}
}
I guess it sort of works in the fact that if I move my mouse the player does rotate but it rotate pretty fast. So I ask am I doing anything wrong? Before you ask, I have looked it up on Google and found some question like this one but none have helped me.
Upvotes: 0
Views: 83
Reputation: 17041
The argument to Graphics2D.rotate
is in radians, not degrees. Try removing Math.toDegrees
from the computation of angle.
Reference here.
Updated:
Per this comment, getLocation
gives the mouse position in screen coordinates, not in the user coordinates of your Graphics2D
. You need to convert the coordinates, but how to do that will be specific to your game library.
Updated 2: Assuming GameObject
extends java.awt.Component
somehow, try getLocationOnScreen
(reference here, from the comment noted above):
Point me_absolute = getLocationOnScreen()
int centerX = (int) (mouse.getX() - me_absolute.getX());
int centerY = (int) (mouse.getY() - me_absolute.getY());
Upvotes: 1