Search code examples
javaslick2d

Spirte is drawn under the background


I'm developing a StateBasedGame in Slick2D (just for learning purposes) and I've encountered a problem.

walkingRight.draw(0,250);

This animation gets drawn under the background sprite. I have no idea how to make it come on top of it. I can't see it at all.

Full code:

    package gamelogic;

import org.lwjgl.input.Mouse;
import org.newdawn.slick.*;
import org.newdawn.slick.gui.MouseOverArea;
import org.newdawn.slick.state.*;

public class Level extends BasicGameState {

    // INITIATE IMAGES
    public Image background;
    public Image title;
    public Image playButton;
    public Image exitButton;

    public Animation walkingRight;
    public Animation playerIdle;
    public int[] duration = {200, 200, 200, 200, 200};
    public int durationIdle[] = {200, 200}; 


    // INITIATE VARIABLES FOR TITLE'S POSITION
    public float menuPosX;
    public float menuPosY;

    public Player player;

    // __CONSTRUCTOR
    public Level(int state) {

    }

    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
        background = new Image("res/levelbg.png");
        Image[] walkRight = { new Image("res/player/snap0.png"), new Image("res/player/snap1.png"),
                new Image("res/player/snap2.png"), new Image("res/player/snap3.png"), new Image("res/player/snap4.png")};
            Image idle[] = { new Image("res/player/snap0.png"), new Image("res/player/snap1.png")};

            this.walkingRight = new Animation(walkRight, this.duration, false);
            this.playerIdle = new Animation(idle, this.durationIdle, false);        

    }

    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
        background.draw(0,0);
        playerIdle.draw(0,0);
    }

    public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
        Input input = gc.getInput();

            walkingRight.draw(0,250);

    }   

    public int getID() {
            return 1;
        }   
    }

Could you guys please help me with that?


Solution

  • Okay, I've found the solution. Instead of drawing the animation inside the update() function, you should draw it only in render() function once with variables as coordinates. In the update() function you will then change the coordinates and just assign a different animation to the animation variable.