简体   繁体   中英

Simple 2d Java game issue

This seems like an easy-fix however I just can't seem to get it, xMove represent moving on the x-axis, y for the y-axis. Currently while my player object is colliding downwards with a tile (standing on the ground) the sprite will be facing right. I want my player to face left if I have been moving left just before that. So basically I need a way to remember what way my character is facing and return that to the yMove == 0 part of my code. Could anyone give me any advice?

private BufferedImage getCurrentAnimationFrame(){ //set Player animations when moving


    if(xMove > 0){
        facingRight = true;
        facingLeft = false;
        return animRight.getCurrentFrame();

    }
    if(xMove < 0){
        facingLeft = true;
        facingRight = false;
        return animLeft.getCurrentFrame();
    }
    if(yMove > 0){
        return Assets.playerFall;
    }

    if(yMove < 0){
        return Assets.playerFall;
    }
    if(yMove == 0){
        return Assets.playerFacingRight;
    }

        return null;
}

Edit: I tried messing around with booleans to return different sprites eg if(facing Left){return Assets.playerFacingLeft} however doing this somehow doesn't return an image at all.

Assuming that you considered x and y axis like this :-

在此处输入图片说明

if(xMove > 0){
    facingRight = true;
    facingLeft = false;
    return animRight.getCurrentFrame();

}
if(xMove < 0){
    facingLeft = true;
    facingRight = false;
    return Assets.playerFacingLeft; // here make the player turn left
}
if(yMove > 0){
    return Assets.playerFall
}

if(yMove == 0){
    return Assets.playerFacingRight;
}
if(yMove < 0){
   // fall down or do nothing if you need it to do nothing you can avoid this check or set ymov back to 0
  yMove = 0;
}

    return null;

You just need to rearrange your code: Handle the y-axis movement first. If there's no vertical movement, then check horizontal movement. I added the final if(facingLeft) statement to handle the situation when the player is neither falling nor standing still:

private BufferedImage getCurrentAnimationFrame(){ //set Player animations when moving

    if(yMove > 0){
        return Assets.playerFall;
    }

    if(yMove < 0){
        return Assets.playerFall;
    }
    if(xMove > 0){
        facingRight = true;
        facingLeft = false;
        return animRight.getCurrentFrame();
    }
    if(xMove < 0){
        facingLeft = true;
        facingRight = false;
        return animLeft.getCurrentFrame();
    }

    if(facingLeft){
        return animLeft.getCurrentFrame();
    } else {
        return animRight.getCurrentFrame();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM