[java] Drawing 2D sprites with BufferStrategy

Started by
3 comments, last by Son of Cain 17 years, 11 months ago
I am using BufferStrategy with two buffers to draw on a awt.Canvas that is inside of a JFrame. So I am trying to get this animated sprite to appear correctly on the screen, but I ran into trouble. Unless the background is cleared somehow after each paint(), the last frame remains on the canvas until a blob remains where my animated sprite was. I figured out how to fix it by drawing a rectangle of white ever time at the beginning of the paint() function, like so: (code tags don't fail me now!)

public void paint(){
        Graphics2D g = (Graphics2D) canvas.getBufferStrategy().getDrawGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0,0,640,480);

        *draw stuff to g*

        g.dispose();
        canvas.getBufferStrategy().show();
    }
However, I imagine once I start using background images, this will become very innefficient. How do I selectively manipulate the background of my canvas?
Advertisement
I think the answer to this question depends on whether the background moves along with the sprite or not. For example, if you have a player sprite in the middle of the screen and you walk to the right, does the background scroll? If so, then you have to render the entire background again anyway, so just render the whole thing.

Otherwise it is a valid question and I am eager to hear the replies.
As Kev said, it depends on the scrolling of the background. To scroll, you calculate the offset of the player's position, paint() the background image based on it, then your tiles, and then you iterate over your sprites to draw them - it will appear to you that they have moved, but in fact, they never leave the center of the screen, the terrain moves, not the sprites.
a.k.a javabeats at yahoo.ca
I see your point about having to update the background anyways if the BG is scrolling, which is problably what most games will do, including mine.

I guess my question is answered then, but I am still curious because I have limited experience with other libraries like Simple Direct Media Layer, and they use "blitting," where you can copy a rectangular area of any given image to a rectangular area of a destination image. Are there any comparable operations possible in Java?

Thanks
I don't know the Java 2D API well enough to answer that, but I guess you can do that easily. In OpenGL, you can use glReadPixels(), so using a Java OGL binding might do the trick. In pure Java 2D, there are means to access the byte array corresponding to the pixels, though I don't know the methods to name them for you. :D
a.k.a javabeats at yahoo.ca

This topic is closed to new replies.

Advertisement