Search code examples
javagraphics2d

Java 2D Game rotate to mouse glitch?


I am making a game in Java (No Libraries). It's a 2D top-down game where the player can walk and is faced towards the mouse cursor.

public Player(int x, int y, int health, int tileId) {
    super(x, y, health);
    tile = new Tile(tileId, false);
    mouseInput = new MouseHandler(screen);
}
public void tick() { // Executed by game tick.
    // x = playerX and y = playerY

    int cursorX = mouseInput.getMousePos()[0];
    int cursorY = mouseInput.getMousePos()[1];

    float X = cursorX - x;
    float Y = cursorY - y;

    rotation = Math.atan2(Y, X);
}

It looks good as long the player is at (0,0) If the player moves and the mouse coordinates become negative it begins to show strange behaviour (Look at video below)

Youtube: https://www.youtube.com/watch?v=M6ZHCrWvt3Y

The rotation of the sprite is done in another class 'Screen.java'

By using:

if (rotation < 360)
    rotation++
else
    rotation = 0

I verified that the rotation is working correctly.

EDIT:

public BufferedImage rotate(BufferedImage img, double degree) {
    AffineTransform tx = new AffineTransform();
    tx.rotate(degree, 4, 4);

    AffineTransformOp op = new AffineTransformOp(tx,AffineTransformOp.TYPE_BILINEAR);
    BufferedImage image = op.filter(img,null);
    return image;
}

Solution

  • Okay i fixed it.

    The problem was the game scale i am making an 2d game and set the width, height and the scale. But i didn't divide the mouseX and mouseY by the scale.

    public void mouseMoved(MouseEvent e) {
        mouseX = e.getX() / game.getScale();
        mouseY = e.getY() / game.getScale();
    }
    

    I found the problem by accident when messing with the gamescale.