¿Cómo puedo animar la posición de una forma?

¿Cómo cambio el código para permitir que una elipse se mueva en lugar de una imagen?

Sé que tengo que usar la clase Graphics2D...
y creo que tengo que añadir Ellipse al Panel ..
como

ArrayList shapeArray = new ArrayList();
public MyPanel(){
Shape s;
s= new Ellipse2D.Float(0, 0, 80, 50);
shapeArray.add(s);

¿Cómo puedo hacer que funcione?

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

class MyPanel extends JPanel implements ActionListener{
    private final int WIDTH = 500;
    private final int HEIGHT = 300;
    private final int START_X = 0;
    private final int START_Y = 250;
    private BufferedImage image;
    private Timer timer;
    private int x, y;
    
    public MyPanel() {
        setBackground(Color.BLACK);
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setDoubleBuffered(true);
        File input = new File("starship.png");
        try {
            image = ImageIO.read(input);
        } catch(IOException e) {
            e.printStackTrace();
        }
        x = START_X;
        y = START_Y;
        timer = new Timer(20, this);
        timer.start();
    }
    
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, x, y, this);
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        x+=1;
        y-=1;
        if(x>WIDTH) {
            x=START_X;
            y=START_Y;
        }
        repaint();
    }
}
public class MyFrame extends JFrame {
    public MyFrame() {
        add(new MyPanel());
        setTitle("Test");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 300);
        setVisible(true);
    }
    public static void main(String[] args) {
        new MyFrame();
    }
}

Pregunta hecha hace 3 años, 4 meses, 29 días - Por scriptsculptorbf10


2 Respuestas:

  • Para animar la posición de una elipse en lugar de una imagen, simplemente necesitas realizar algunas modificaciones en el código existente. Aquí te muestro cómo puedes hacerlo:

    • En lugar de utilizar una imagen, crearemos un objeto de tipo `Ellipse2D.Float` para representar la elipse en el panel.
    • En el método `paintComponent`, utilizaremos un `Graphics2D` en lugar de un `Graphics` para poder dibujar la elipse.
    • En el método `actionPerformed`, actualizaremos las coordenadas de la elipse en lugar de las coordenadas de la imagen.
    • Modificaremos la forma en que se reinician las coordenadas al llegar al borde derecho de la pantalla.

    A continuación, te muestro el código modificado:

    java
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Ellipse2D;
    import java.util.ArrayList;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    
    class MyPanel extends JPanel implements ActionListener {
        private final int WIDTH = 500;
        private final int HEIGHT = 300;
        private final int START_X = 0;
        private final int START_Y = 250;
        private Timer timer;
        private Ellipse2D.Float ellipse;
    
        public MyPanel() {
            setBackground(Color.BLACK);
            setPreferredSize(new Dimension(WIDTH, HEIGHT));
            setDoubleBuffered(true);
    
            ellipse = new Ellipse2D.Float(0, 0, 80, 50);
    
            timer = new Timer(20, this);
            timer.start();
        }
    
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setColor(Color.WHITE);
            g2d.fill(ellipse);
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            int dx = 1; // incremento en la coordenada x
            int dy = -1; // decremento en la coordenada y
    
            ellipse.x += dx;
            ellipse.y += dy;
    
            if (ellipse.x > WIDTH) {
                ellipse.x = START_X;
                ellipse.y = START_Y;
            }
    
            repaint();
        }
    }
    

    Con estas modificaciones, ahora la elipse se moverá de manera animada en el panel. Puedes ajustar los valores de dx y dy para cambiar la velocidad y dirección del movimiento. Espero que esta explicación y código te haya sido útil. ¡Déjame saber si tienes alguna otra pregunta!

    Respondida el Dec 17, 2020 a las 09:22 - por Gpt

    Votos positivos: 0 | Votos negativos: 0

  • Puedes animar la posición de una forma utilizando la clase Graphics2D y el método fill, que dibuja una forma rellena. Para hacer esto, necesitarás crear una instancia de Ellipse2D.Float y añadirla a un ArrayList de formas. Luego, en el método paintComponent, dibuja la forma usando el método fill y actualiza su posición utilizando un Timer.

    Aquí tienes un ejemplo de cómo puedes cambiar tu código para animar una elipse:

    
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.geom.Ellipse2D;
    import java.util.ArrayList;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    
    class MyPanel extends JPanel implements ActionListener{
        private final int WIDTH = 500;
        private final int HEIGHT = 300;
        private final int START_X = 0;
        private final int START_Y = 250;
        private ArrayList shapes = new ArrayList<>();
        private Timer timer;
        private int x, y;
    
        public MyPanel() {
            setBackground(Color.BLACK);
            setPreferredSize(new Dimension(WIDTH, HEIGHT));
            setDoubleBuffered(true);
            Ellipse2D shape = new Ellipse2D.Float(START_X, START_Y, 80, 50);
            shapes.add(shape);
    
            x = START_X;
            y = START_Y;
            timer = new Timer(20, this);
            timer.start();
        }
    
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (Ellipse2D shape : shapes) {
                g.setColor(Color.WHITE);
                g.fill(shape);
            }
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            for (Ellipse2D shape : shapes) {
                shape.setFrame(shape.getX() + 1, shape.getY() - 1, shape.getWidth(), shape.getHeight());
                if(shape.getX()>WIDTH) {
                    shape.setFrame(START_X, START_Y, shape.getWidth(), shape.getHeight());
                }
            }
            repaint();
        }
    }
    
    public class MyFrame extends JFrame {
        public MyFrame() {
            add(new MyPanel());
            setTitle("Test");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(500, 300);
            setVisible(true);
        }
        public static void main(String[] args) {
            new MyFrame();
        }
    }
    
    

    En este código, el ArrayList shapes almacena la elipse. En el método paintComponent, el bucle for dibuja cada elipse en el ArrayList utilizando el método fill. En el método actionPerformed, el bucle for actualiza la posición de cada elipse y comprueba si ha salido de los límites del panel. Si lo ha hecho, la elipse se restablece a su posición inicial.

    Ten en cuenta que este código solo anima una elipse. Si quieres animar múltiples formas, tendrás que añadirlas al ArrayList y actualizar sus posiciones en consecuencia.

    Respondida el Dec 17, 2020 a las 09:28 - por Gemini

    Votos positivos: 0 | Votos negativos: 0