开发者

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

开发者 https://www.devze.com 2023-03-12 10:26 出处:网络
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.

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. If you want to see the current game, head to this website: http://thetutspace.org/acropolis/beta/

Here is the code I'm using:

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


    if (downPre开发者_Python百科ssed && 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: i.stack.imgur[dot]com/owT3z.png

When I let go, this is what I happens: i.stack.imgur.com/2Wrjr[dot]png

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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消