Hi I have a tile based game and I would like to know how to animate the grass image this is what I have so far:

public class dirt extends block{

    float frame = 0;
    public dirt(int x,int y){
        this.x = x;
        this.y = y;
        r = new Rectangle(x - (int)tilemap.camx,y - (int)tilemap.camy,20,20);
        solid = false;


    public void tick(){

        int tester = (int)(frame +.1);

        if(tester < 3){
            frame = 0;


    public void render(Graphics g){
        ImageIcon i62 = new ImageIcon("res/grasssheet.png");
        img = i62.getImage();
        g.drawImage(img, x - (int)tilemap.camx,y-(int)tilemap.camy,x+20,y+60/***/,0,20*(int)frame,60,20*(int)frame + 20,null);
        //g.drawImage(img, x- (int)tilemap.camx,y-(int)tilemap.camy, null);


This kinda works but I don't why all the images glitch out.

I think I need an image observer but I don't understand that so if that's the problem explain what I have to please.

  • 2
    \$\begingroup\$ I don't understand what you're asking and I'm not sure you do either. What are you trying to do? What does "kinda works" mean? Why do you think you need an image observer? Please edit the question to clarify. \$\endgroup\$
    – Anko
    Mar 25 '14 at 13:50
  • \$\begingroup\$ Could it be that you are using a float for frame instead of a int? \$\endgroup\$
    – koss
    Mar 27 '14 at 15:06

It looks like you are drawing directly to the graphics objects instead of buffering. Have you seen the documentation?

Java has a BufferStrategy class that might help you. You should do your drawing off-screen, then switch the view using the BufferStrategy object, removing all flickering.

You might want to look at some Java game engines though: They already do a lot of the heavy lifting for you, letting you focus on the game logic and play.


Your question is too vague.
What do you mean by "glitch out"?

From the look of the drawImage I assume that you want to draw a single 'frame' (20px*20px) from the spritesheet? That's not what I see there.

g.drawImage(img.getSubimage((frame*20),0,20,20), x - (int)tilemap.camx, y-(int)tilemap.camy, null);

Also, you shouldn't be reloading the images on every render call. Load it once and, for example, pass it in the constructor, or, better yet, create a tile 'Type', load the image once there and give each tile a reference to a tile type.
(And is there a reason you are loading it as an ImageIcon as opposed to, say, a BufferedImage?)


Not the answer you're looking for? Browse other questions tagged or ask your own question.