Character sprite rotation

So I’m new to coding in Java.

I’m making an endless runner, so the character never stops, only jumps. I have 8 sprites for running animation, and one for jumping.
Currently I’ve been using just a single image with a simple line of code assinging a .png to a BufferedImage, and then return it to my level class, where I use Graphics2D to draw it. I haven’t gotten to jumping part yet but the idea was something in the lines of checking if the character is jumping and if he is not then the rotation presumes.

How should I go about to make the sprites rotate? I tried a couple of simple ways, like doing a for loop with thread sleep but the image didn’t update.

I wouldn’t suggest that you use a for loop, and certainly not Thread.sleep() while painting. What i would do is loading all the images needed at the start and saving them in an array or an arraylist. Then create a counter to use as an index for the sprite image you need everytime you call paint() or repaint(). So lets say you have the main game loop, and you call repaint() in that loop, you would have something like this:


//Loop
while(someCondition){

repaint();
if(running){
counter++;
     if(counter > 7){
     counter = 0;
     }
   }
}

//and then inside your paint() method you do this:

if(running){
g2d.drawImage(list[counter],x,y,null);
} else{
g2d.drawImage(runningSpriteImage,x,y,null)
}
// the list array is an array of BufferedImage containing your sprites

You can rotate your buffered image using an AffineTransform object (which is an object that applies linear transformations). Lets say that you store the rotation of a sprite as a variable, then the following will rotate the image if the rotation is != 0.


public void render(Graphics2D g) {
        if (rotation != 0.0f) {
            AffineTransform at = new AffineTransform();

            // go to sprite position
            at.setToTranslation(spriteX, spriteY);

            // translate to centre of sprite
            at.translate(spriteWidth() / 2, spriteHeight() / 2);

            // rotate about the centre of sprite
            at.rotate(Math.toRadians(rotation));

            // translate back to sprite position
            at.translate(-spriteWidth() / 2, -spriteHeight() / 2);

            // draw the sprite using the affine transform object
            g.drawImage(sprite, at, null);
        }
        else {
            g.drawImage(sprite, spriteX(), spriteY(), null);
        }
    }

For speed, I would have the rotation done already - don’t rotate it at runtime, just have say 20 sprites of rotated ones and use a counter to index
through them. That way you can then just use drawImage without doing any runtime rotation calculations which are costly.