I am building an isometric game environemnt and i want to be able to pan the camera around the map by holding the right mouse button, can someone talk me through the logic for this please, i have made an attempt and tried a number ways. I can get the camera to move correctly the first time but when i click and hold the second time the camera resets itself, thanks in advance for any help
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class CameraMovementTest extends JPanel{
private Timer timer;
private int DELAY = 10;
private CustomMouseListener mouseListener;
private int positionX = 0, positionY = 0;
public CameraMovementTest() {
mouseListener = new CustomMouseListener();
this.addMouseListener(mouseListener);
this.addMouseMotionListener(mouseListener);
this.setSize(500,500);
this.setVisible(true);
//Swing Timer
timer = new Timer(DELAY, new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
update();
repaint();
validate();
}
});
timer.start();
}
private void update() {
if(mouseListener!=null){
positionX = mouseListener.getX();
positionY = mouseListener.getY();
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.fillRect( positionX, positionY, 300,300);
}
public class CustomMouseListener implements MouseListener, MouseMotionListener {
private int positionX = 0, positionY = 0;
private int mouseClickX, mouseClickY;
@Override
public void mousePressed(MouseEvent evt) {
if(SwingUtilities.isRightMouseButton(evt)) {
mouseClickX = evt.getX();
mouseClickY = evt.getY();
}
}
@Override
public void mouseDragged(MouseEvent evt) {
if(SwingUtilities.isRightMouseButton(evt)) {
positionX = mouseClickX - evt.getX();
positionY = mouseClickY - evt.getY();
}
}
@Override
public void mouseMoved(MouseEvent arg0) {}
@Override
public void mouseClicked(MouseEvent arg0) { }
@Override
public void mouseEntered(MouseEvent arg0) { }
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
public int getX(){
return positionX;
}
public int getY(){
return positionY;
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(new Dimension(500,500));
f.setContentPane(new CameraMovementTest());
}
});
}
}
I can get the camera to move correctly the first time but when i click and hold the second time the camera resets itself, thanks in advance for any help
Then you're resetting something you shouldn't reset. If you'd show us your code which doesn't work correctly we could try to find the mistake. \$\endgroup\$ – tkausl Oct 25 '15 at 14:24