Search code examples
javaswinggraphicsawtgraphics2d

AWT Graphics not Translating Correctly


I'm making a simple 2-D game for which I'd like to move the camera with the mouse. There are loads of better ways to do this, I'm sure, but I decided to try out the Graphics2D method setTransform().

AffineTransform at = new AffineTransform();
at.translate(mousex, 0);

Graphics2D g2d = (Graphics2D)g.create();
g2d.setTransform(at);

However, the graphics don't translate linearly with the mouse, as you can see from the images below. For the first few pixels it seems to move correctly, but it kind of slows down later?

By the way, the mouse is indicated by the blue circle.

enter image description here

enter image description here

When the mouse is near the edge of the frame, the graphics moves almost linearly with it to the right.
When the mouse is dragged further to the right, the graphics moves with it, but with a kind of lag (it shouldn't)

The white border around the blocks represents the outline of the graphics that should be moving.

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

import javax.swing.*;

public class Bruh extends JPanel implements MouseMotionListener
{
    int mousex = 0;

    public static void main(String[] args) {
        JFrame f = new JFrame();
        
        f.setSize(500, 500);
        f.setLocationRelativeTo(null);
        
        f.setUndecorated(true);
        
        f.add(new Bruh());
        
        f.setVisible(true);
    }

    Bruh()
    {
        setBackground(Color.ORANGE);

        addMouseMotionListener(this);
    }

    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        AffineTransform at = new AffineTransform();
        at.translate(mousex, 0);

        Graphics2D g2d = (Graphics2D)g.create();
        g2d.setTransform(at);

        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 100, 100, 100);

        g2d.dispose();

        g.setColor(Color.BLUE);
        g.fillOval(mousex-5, 200-5, 10, 10);

        repaint();
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        mousex = e.getX();
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        mousex = e.getX();
    }
}

TL;DR

The setTransform(AffineTransform at) function of Graphics2D isn't working as intended. Any help is appreciated :)


Solution

  • Okay so I got the answer. The problem isn't in my code, or with my touchpad scrolling.

    On my laptop, I had set the scaling of the display to 125%, causing everything to work normally EXCEPT apps that use default scaling - Java being one of them.

    The problem was that my mouse moved correctly (because that's what mice do) but the in-built graphics of java were responding to the default scaling of the display i.e. 125%. So everything was moving 1.25 times slower than expected.