How to change variables stored inside mouseMoved method in MouseMotionListener Java Class

222 views Asked by At

I am trying to write a mouse listener for my game. The basic idea is that I use mouse listener to (constantly update) track the x and y coordinates of my cursor and change the position of the player accordingly. I decided to use the mouseMoved method inside MouseMotionListener to accomplish this. I am supposed to press on the screen once in order to initiate mouse tracking of player, and once to stop. However, it seems my variables will not update inside mouseMoved. How do I update the variables inside the method?

private Handler handler;
public static int vel=5;
boolean pressed = false;
int run=0;

int x;
int y;

public  mouseListener(Handler handler){
    this.handler = handler;

}
public void mouseClicked(MouseEvent event) {
    run++;

}


public void mouseMoved(MouseEvent event) {

    this.x = event.getX() - 16;
    this.y = event.getY() - 16;
    System.out.println("Click"+run);
    int trun=run;

    if(trun%2==1) {
        System.out.println(x+" "+y);
        updateField(x,y);
    }


}

public void updateField(int tempx, int tempy) {
    int x=tempx;
    int y=tempy;
    for(int i=0; i<handler.object.size();i++){
        GameObject tempObject = handler.object.get(i);

        if(tempObject.getID()== ID.Player){

            if(x>tempObject.getX()) {
                tempObject.setVelX(vel);
            }
            if(x<tempObject.getX()) {
                tempObject.setVelX(-1*vel);
            }
            if(x==tempObject.getX()) {
                tempObject.setVelX(0);
            }
            if(y>tempObject.getY()) {
                tempObject.setVelY(vel);
            }
            if(y<tempObject.getY()) {
                tempObject.setVelY(-1*vel);
            }
            if(y==tempObject.getY()) {
                tempObject.setVelY(0);
            }
            if(pressed==false) {
                tempObject.setVelY(0);
                tempObject.setVelX(0);
            }

        }
    }

}

By the end result, I should be able to click on the screen once, and the player should start following my mouse. I should then be able to click again to turn it off. Instead, the x and y values are updated but the player does not move and the on/off variable does not update inside mouseMoved().

0

There are 0 answers