I am creating a very simple Java Slick game in 2d. I can use the renderer method int the class that extends the BasicGameState but i would like to render into my game container using a DarwMap class.
Here is my source code for the game and the not working DrawMap class:
public class GamePlay extends BasicGameState{
DrawMap map;
public GamePlay(int state){
}
@Override
public void init(GameContainer arg0, StateBasedGame arg1) throws SlickException {
// TODO Auto-generated method stub
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
map.render();
}
@Override
public void update(GameContainer arg0, StateBasedGame arg1, int arg2) throws SlickException {
// TODO Auto-generated method stub
}
@Override
public int getID() {
// TODO Auto-generated method stub
return 1;
}
}
and the next class
public class DrawMap {
//size of the map
int x,y;
//size of the tile
int size;
//tile
Image tile;
//creator
public DrawMap(GameContainer gc, int x, int y, int size){
this.x = x;
this.y = y;
this.size = size;
}
public void render() throws SlickException{
tile = new Image("res/Tile.png");
for(int i=0; i<(y/size); i++){
for(int j=0; j < (x/size); j++){
tile.draw(j*size, i*size, 2);
}
}
}
}
I know that this is wrong but if someone could help me figure it out and solve my problem of drawind with a DrawMap class.
I don't see it in your constructor, but I'm assuming you're creating your map
instance there.
Now, to draw onto the screen (and this is valid to Slick and Java2D in general) you need a Graphics
object, that represents a graphics context, which is the object that manages to put your data into the screen. In the case of Slick2D, you can get the graphics from the GameContainer
using a call to it's getGraphics
method. Then, you can draw your image into the screen calling the drawImage
method on the Graphics
object you just obtained.
Here is an example, passing the graphics context as a parameter of the DrawMap
's render
method:
public class GamePlay extends BasicGameState{
DrawMap map;
...
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
map.render(gc.getGraphics());
}
...
}
And the DrawMap
class...
public class DrawMap {
Image tile;
...
public void render(Graphics g) throws SlickException {
// your logic to draw in the image goes here
// then we draw the image. The second and third parameter
// arte the coordinates where to draw the image
g.drawImage(this.tile, 0, 0);
}
}
Of course, you can go ahead and draw directly into the Graphics
object.