Reputation: 249
I'm making Pong game, I can't get the player and AI paddles to move correctly. This explanation may be a little chaotic.
First, the player's paddle. I will make a separate question for AI to keep the length of this post within reason.
HEIGHT
and WIDTH
defines paddle size, image
is texture for the paddle
double mouseY = MouseInfo.getPointerInfo().getLocation().getY();
if (mouseY < getHeight() - HEIGHT) {
paddleLeft.setLocation(2 * WIDTH, mouseY);
image.setLocation(2 * WIDTH, mouseY);
image.sendToFront();
} else {
// stop paddle from sliding off screen
paddleLeft.setLocation(2 * WIDTH, getHeight() - HEIGHT);
image.setLocation(2 * WIDTH, getHeight() - HEIGHT);
image.sendToFront();
Player's paddle is being controlled by mouse. Right now, when i move my cursor to the top of my screen, my paddle (top border) touches the top of the window. This could be considered correct but I don't like it. If i move the window to the center of my screen, i need to move my mouse off the screen to steer. It works like this:
and I want the paddle's top border to be parallel with cursor Y coordinate. I tried using different code to get mouse position with:
addMouseListeners();
and
public void mouseMoved(MouseEvent e) {
mouseY=e.getYOnScreen();
}
but then my cursor still is not aligned with the paddle and I can only move my paddle within range shown on screenshot 2: (with cursor on top window border)
Upvotes: 2
Views: 763
Reputation: 40335
Subtract the frame's X and Y screen positions from the screen mouse coordinate to get the offset in the frame, or add a proper MouseListener
to the frame itself, which will provide mouse position in window client coordinates.
The listener approach is generally better anyways, as it means you can also, e.g., add other components to your window without affecting mouse code; it keeps everything self-contained in the game frame.
Upvotes: 1