Search code examples
javaapplet

Making a sprite move, need the sprite to stay in the postion he last moved in


I'm making a Java game, and when the user presses some keys, the sprite moves in that direction, and it changes the sprite to match the direction that the user is inputting.

Here is the code I'm using:

int x_posI = (int) x_pos;
int y_posI = (int) y_pos;

if (downPressed && leftPressed) {
        g.drawImage(hero225, x_posI, y_posI, this);
        spr270 = false;
} else if (downPressed && rightPressed) {
        spr270 = false;
        g.drawImage(hero135, x_posI, y_posI, this);
} else if (upPressed && rightPressed) {
        spr270 = false;
        g.drawImage(hero45, x_posI, y_posI, this);
} else if (upPressed && leftPressed) {
        g.drawImage(hero315, x_posI, y_posI, this);
        spr270 = false;
} else if (leftPressed == true) {
        g.drawImage(hero270, x_posI, y_posI, this);
        spr270 = true;
} else if (rightPressed == true) {
        g.drawImage(hero90, x_posI, y_posI, this);      
        spr270 = false;
} else if (upPressed == true) {
        g.drawImage(hero, x_posI, y_posI, this);
        spr270 = false;
} else if (downPressed == true) {
        g.drawImage(hero180, x_posI, y_posI, this);     
        spr270 = false;
}
        else{
                g.drawImage(hero, x_posI, y_posI, this);
        }
if(spr270) {
        g.drawImage(hero270, x_posI, y_posI, this);
}

When I press LEFT, this is what happens:

When I let go, this is what happens:

How can I make it so the character stays facing left?


Solution

  • This is inside paint( Graphics g ) method, right?

    Add volatile Image field sprite to your class ("protected volatile Image sprite;"). Change logic to:

    int x_posI = (int) x_pos;
    int y_posI = (int) y_pos;
    
    if (downPressed && leftPressed) {
        this.sprite = hero225;
    } else if (downPressed && rightPressed) {
        this.sprite = hero135;
    } else if (upPressed && rightPressed) {
        this.sprite = hero45;
    } else if (upPressed && leftPressed) {
        this.sprite = hero315;
    } else if (leftPressed == true) {
        this.sprite = hero270;
    } else if (rightPressed == true) {
        this.sprite = hero90;
    } else if (upPressed == true) {
        this.sprite = hero;
    } else if (downPressed == true) {
        this.sprite = hero180;
    }
    
    // this.sprite will contain value set on last "movement"
    g.drawImage(this.sprite, x_posI, y_posI, this);