I have a bit of a problems with the mousePressed and mouseDragged events. I am trying to create a Space Shooter game and I want the player to be able to shoot by pressing and moving around the mouse. The big problem I think I have it's with the mouseDragged event. To be more specific: when I press the mouse button mousePressed is called and it runs perfectly, then when I move the mouse around (still keeping the mouse pressed) mouseDragged gets in and it works fine also, but when I stop moving the mouse (note I still have it pressed) my Spaceship stops firing and I'm not sure why.
This is the code:
private void initShootingThread(final MouseEvent e) {
new Thread() {
public void run() {
do {
playerShoot(e);
} while (buttonPressed);
}
}.start();
}
// // PLAYER SHOOTING EVENTS ////
public void mouseClicked(MouseEvent e) {
playerShoot(e);
}
public void mousePressed(MouseEvent e) {
buttonPressed = true;
initShootingThread(e);
}
public void mouseDragged(MouseEvent e) {
buttonPressed = false;
playerShoot(e);
}
public void mouseReleased(MouseEvent e) {
buttonPressed = false;
}
Thank you in advance!
2 Answers 2
As long as you drag the mouse you manually invoke the playerShoot(e) method from the mouseDragged() method..
However, your mouseDragged() method sets your buttonPressed variable to false so as soon as you stop dragging your main loop stops.
So don't set the buttonPressed variable to false.
3 Comments
Finally found the answer! camickr you were right, my problem was in the playerShoot method.
To be more specific that MouseEvent e from the method's parameters was taking care of the position of the ship and also of the bullet starting place and since it was final I don't think it updated itself correctly when the method was called. Now the position of the ship is updated "manually" accordingly to x and y variables.
Now my code is something like this and it works like a charm:
private void initShootingThread() {
new Thread() {
public void run() {
do {
playerShoot();
} while (buttonPressed);
}
}.start();
}
// // PLAYER SHOOTING EVENTS ////
public void mouseClicked(MouseEvent e) {
playerShoot(e);
x = e.getX();
y = e.getY();
}
public void mousePressed(MouseEvent e) {
buttonPressed = true;
initShootingThread();
x = e.getX();
y = e.getY();
}
public void mouseDragged(MouseEvent e) {
playerShoot();
x = e.getX();
y = e.getY();
}
public void mouseReleased(MouseEvent e) {
buttonPressed = false;
}
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
}