Foros del Web » Programación para mayores de 30 ;) » Java »

parpadeo al pintar imagenes

Estas en el tema de parpadeo al pintar imagenes en el foro de Java en Foros del Web. Hola a todos, estoy haciendo un juego en 2D con java y tengo un problema en el pintado de imagenes, para pintar el mapa utilizo ...
  #1 (permalink)  
Antiguo 15/10/2010, 03:14
 
Fecha de Ingreso: octubre-2008
Mensajes: 118
Antigüedad: 15 años, 6 meses
Puntos: 2
parpadeo al pintar imagenes

Hola a todos, estoy haciendo un juego en 2D con java y tengo un problema en el pintado de imagenes, para pintar el mapa utilizo la libreria javamappy. El mapa lo pinta en un doble buffer y despues pinto yo mi sprite. El problema es que se nota un parpadeo en el sprite ya que primero pinta el mapa y luego mi sprite.
Nose como tengo que hacer para añadir mi sprite al doble buffer para que no se note este parpadeo. El codigo es este:

Código:
public class VPrincipal extends JFrame implements Runnable{


        Thread miThread1= new Thread();
        Thread miThread2=new Thread();
        private static String    mapFileName        = "mapa.FMP";
    public static int         windowWidth     = 820;        // dimensions in pixels
    public static int         windowHeight    = 556;
    private static int         speedX            = 2;        // no of pixels to move the map each frame
    private static int         speedY            = 2;
    private static int         refreshRate     = 30;        // no of milli-seconds that should pass between each frame, 33 ~ 30Hz
    private    static boolean    running         = false;    // is set to true if the map is moving

    private Image             doubleBuffer;
    private    MapViewer        mapViewer;
    private    LayerViewer        layerViewer;
    //private KeyboardInput    keyboardInput    = new KeyboardInput();
    private static Class     renderType        = JDK12Renderer.class;

        public VPrincipal(){
            this.addKeyListener(new KeyListener() {

            public void keyTyped(KeyEvent e)
            {

            }

            public void keyPressed(KeyEvent e)
            {
                if (!miThread1.isAlive() && !miThread2.isAlive()){
                    int codigoTecla= e.getKeyCode();
                    if (codigoTecla>=37 && codigoTecla<=40){
                        HiloAnimarHeroe hiloAnda = new HiloAnimarHeroe(codigoTecla, miThread2, mapViewer, layerViewer);
                        miThread1 = new Thread(hiloAnda);
                        miThread1.start();
                    } else if(codigoTecla==32){
                        /*HiloAtaqueHeroe hiloAtque = new HiloAtaqueHeroe(pPrincipal);
                        miThread1 = new Thread(hiloAtque);
                        miThread1.start();
                         * */
                    } else if(codigoTecla==10){
                        FuncionesNPC.hayNPC(FuncionesHeroe.getHeroe());
                    }
                }
            }

            public void keyReleased(KeyEvent e)
            {

            }
        });
        }

    public void initialise(){
        BufferedInputStream inputStream=null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(mapFileName));
        } catch (FileNotFoundException ex) {
            java.util.logging.Logger.getLogger(VPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }

        // create the viewers, making them render with the given JDK
        Map map     = MapLoader.loadMap(inputStream);
        Renderer r = null;
        try {
            try {
                r = ((Renderer) renderType.getConstructor(new Class[] {Map.class}).newInstance(new Object[] {map}));
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(VPrincipal.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(VPrincipal.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalArgumentException ex) {
                java.util.logging.Logger.getLogger(VPrincipal.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InvocationTargetException ex) {
                java.util.logging.Logger.getLogger(VPrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (NoSuchMethodException ex) {
            java.util.logging.Logger.getLogger(VPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            java.util.logging.Logger.getLogger(VPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }
        mapViewer     = new MapViewer(map, r, windowWidth, windowHeight, 0, 0);
        layerViewer = mapViewer.getLayerViewers()[0];
                layerViewer.addPixelX(32*6);
                layerViewer.addPixelY(32*4);
        try { inputStream.close(); } catch (IOException ioe) { /**/ }

        // create double buffer
        doubleBuffer = super.createImage(windowWidth, windowHeight);

    }

    public void run() {
        running = true;

        // the game loop
        while (running) {
            long startTime = System.currentTimeMillis();

            // scroll the map...

            // animate the map...
            mapViewer.updateAnimBlocks();

            // ...and draw it in the buffer
/*
he probado tanto con:
Graphics2D gfx = (Graphics2D)doubleBuffer.getGraphics();
 y con:
gfx.drawImage(FuncionesHeroe.getHeroe().imagen(),50,50,null);
*/
            Graphics2D gfx = (Graphics2D)doubleBuffer.getGraphics();
            //gfx.drawImage(FuncionesHeroe.getHeroe().imagen(),50,50,null);
            layerViewer.draw(gfx, false);
            gfx.setColor(Color.RED);
            gfx.drawString("X: " + layerViewer.getPixelX() + "     Y: " + layerViewer.getPixelY(), 10, 40);
            gfx.dispose();
                        

            // render the buffer to the screen
            super.repaint();

            // rest for the remainder of the jiffy
            long timeTaken = System.currentTimeMillis() - startTime;
            if (timeTaken < refreshRate) {
                try {
                    // Sleep little one, sleep!
                    Thread.sleep(refreshRate - timeTaken);
                } catch (InterruptedException ie) { /**/ }
            } else {
                // give other threads a chance to catch up
                Thread.yield();
            }
        }
    }

    public void paint(Graphics g) {
        if (doubleBuffer != null) {
                        
            // take into account the window border
            Insets insets = super.getInsets();
            g.drawImage(doubleBuffer, insets.left, insets.top, null);
                        FuncionesHeroe.getHeroe().draw(g);
//devuelve el Heroe (Sprite) y llama a su metodo
        }
    }

    public void update(Graphics g) {
        // this prevents the screen being white-washed
        paint(g);
    }



}
y el meto draw del sprite es el siguiente:

Código:
public void draw(Graphics g) {
        g.drawImage(((Image)vSprites.get(frame)),posx,posy,null);
    }

Si alguien tiene una pequeña idea de como solucionar esto me seria de gran ayuda.

Gracias,
Dani.
  #2 (permalink)  
Antiguo 15/10/2010, 12:22
 
Fecha de Ingreso: junio-2010
Mensajes: 59
Antigüedad: 13 años, 10 meses
Puntos: 5
Respuesta: parpadeo al pintar imagenes

Hola:
Veo que tienes toda tu logica, pintado, el hilo, etc. todo en un solo archivo.
Deberia organizar mejor tu codigo, hacer un diagrama de clases de como va estar estructurado tu programa.
En el caso de las animaciones, puede crearte una clase, por decir "pintado" que solo se encargue del pintado, y que extienda de JPanel, y simplemente en su constructor de la clase pones:
Código PHP:
this.setdoublebuffer(true//si no me equivo es asi 
sobreescribis el metodo paint, y ya no deberia parpadear tu programa
Obviamente en el JFrame principal te creas un contenedor, donde lo adicionas tu clase que extiende de JPanel y listo
Suerte
  #3 (permalink)  
Antiguo 16/10/2010, 07:23
 
Fecha de Ingreso: octubre-2008
Mensajes: 118
Antigüedad: 15 años, 6 meses
Puntos: 2
Respuesta: parpadeo al pintar imagenes

Cita:
Iniciado por rodrigo_1986 Ver Mensaje
Hola:
Veo que tienes toda tu logica, pintado, el hilo, etc. todo en un solo archivo.
Deberia organizar mejor tu codigo, hacer un diagrama de clases de como va estar estructurado tu programa.
En el caso de las animaciones, puede crearte una clase, por decir "pintado" que solo se encargue del pintado, y que extienda de JPanel, y simplemente en su constructor de la clase pones:
Código PHP:
this.setdoublebuffer(true//si no me equivo es asi 
sobreescribis el metodo paint, y ya no deberia parpadear tu programa
Obviamente en el JFrame principal te creas un contenedor, donde lo adicionas tu clase que extiende de JPanel y listo
Suerte
DIOS!!!!! muchisimas gracias! gracias a ti he podido solucionar este problema y ahora puedo seguir con mi proyecto, GRACIAS.


Saludos,
Dani.

Etiquetas: imagenes, parpadeo, pintar
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 08:05.