动画背景java游戏 [英] animated background java game

查看:258
本文介绍了动画背景java游戏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



i.stack.imgur.com/yfZdz.pngalt =http://gyazo.com/aebb41b4ef4074823fc46e8e124fc570>



现在我在主类中产生一个小行星但我想为小行星创建一个类,我是这么做的吗?

主类

  public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d =(Graphics2D)g;
if(flag_img)
{
background(g2d);
logo(g2d);
menu(g2d);
太空船(g2d);
crediti(g2d);




$ b $背景函数(现在)



  private void background(Graphics2D g2d)
{

asteroidi_g_x + = r.nextInt(4);
asteroidi_g_y + = r.nextInt(1);
g2d.drawImage(asteroidi_g [0],asteroidi_g_x,asteroidi_g_y,this);

$ / code $


后台函数(我想要的)

  private void background(Graphics2D g2d)
{
asteroid asteroid = new asteroid [10];

和类小行星

  public class asteroid extends JPanel implements ActionListener 
{
private BufferedImage images_asteroid;
private boolean flag_img;

私人JPanel jp;

private int x,y;

public asteroide_grande(JPanel jp)
{
flag_img = true;
x =(jp.getWidth()/ 2);
y =(jp.getHeight()/ 2);
this.jp = jp;

尝试{
images_asterod = ImageIO.read(this.getClass()。getResource(images / asteroid / a1.png));
} catch(IOException e){flag = false;}
}

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(flag_img)
{
g.drawImage(images_asteroid,100,100,this);



$ b @Override
public void actionPerformed(ActionEvent e)
{
x = x-1;
y = y + 1;
repaint();
}

类中的paintcomponent方法不起作用

解决方案


  1. 没有小行星 class extends 的JPanel 。取而代之的是将它作为模型的小行星数据和数据操作方法的类。您还需要一个绘图方法,该方法采用 Graphic 上下文。类似于

      public class Asteroid {
    Image asteroidImage;
    JPanel面板;
    int x,y;

    public Asteroid(JPanel panel,Image image,int x,int y){
    this.panel = panel;
    this.asteroidImage = image;
    this.x = x;
    this.y = y;
    }

    public void drawAsteroid(Graphics g){
    g.drawImage(asteroidImage,x,y,panel);
    }

    public void move(){
    x + = 5;



  2. 现在你有一个小行星模型,你可以创建一个 List > Asteriod 对象并遍历它们并使用它的 drawAsteroid 方法来绘制它们。类似于

      public class GamePanel extends JPanel {
    List< Asteroid>小行星;
    图片asteroidImage;

    public GamePanel(){
    asteroidImage = ...
    asteroids = new ArrayList<>();
    asteroids.add(新的小行星(GamePanel.this,asteroidImage,100,100));
    // add more asteriods
    }

    @Override
    protected void paintComponent(Graphics g){
    super.paintComponent(g); (星号:asteriods){
    asteriod.drawAsteroid(g);
    (Asteriod asteroid:asteriods)
    }
    }
    }


  3. 动画,你会想要使用 javax.swing.Timer 。请参阅如何使用Swing计时器。您需要操作 Timer 中的 Asteriod 数据。使用上面提供的代码,您可以调用它的 move 方法,然后调用 repaint()。类似于

      public GamePanel(){
    ...
    定时器计时器=新计时器(30,新的ActionListener(){
    public void actionPerformed(ActionEvent e){
    Iterator it = asteroids.iterator();
    while(it.hasNaext()){
    Asteroid asteriod = (Asteroid)it.next();
    asteroid.move();
    }
    }
    });

    $ / code>







  4. 您可以在此处此处此处此处此处 p>




    下面是一个完整的例子。你会看到我在 Astreroid 类中包含了一个 Rectangle2D 对象。这只是如果你想检查碰撞检测。您应该将 Rectangle2D x 和/或 y 与每 Asreroid 移动 x y 。然后你可以检查 asteroid.rectangle.intersects(someOtherObject)




      import java.awt。尺寸; 
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Random;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    导入javax.swing.SwingUtilities;
    import javax.swing.Timer;

    public class AsteroidBackground extends JPanel {

    private static final int D_W = 400;
    private static final int D_H = 600;
    BufferedImage asteroidImage;
    BufferedImage背景;
    List< Asteroid>小行星;
    Random random = new Random();
    int countToAddAsteroid = 0;
    int y;

    public AsteroidBackground(){
    try {
    asteroidImage = ImageIO.read(getClass()。getResource(/ resources / small-asteroid.png));
    background = ImageIO.read(getClass()。getResource(/ resources / space.png));
    } catch(IOException ex){
    Logger.getLogger(AsteroidBackground.class.getName()).log(Level.SEVERE,null,ex);
    }
    asteroids = new ArrayList<>();
    y = 0 - asteroidImage.getHeight();

    timer timer = new Timer(40,new ActionListener(){
    public void actionPerformed(ActionEvent e){
    if(countToAddAsteroid> = 25){
    int randX = random.nextInt(D_W);
    asteroids.add(new Asteroid(AsteroidBackground.this,asteroidImage,randX,y));
    countToAddAsteroid = 0;
    }
    countToAddAsteroid ++;
    Iterator it = asteroids.iterator();
    while(it.hasNext()){
    Asteroid asteroid =(Asteroid)it.next();
    if( asteroid.y> = D_H){
    it.remove();
    } else {
    asteroid.move();
    }
    }
    重绘();
    }
    });
    timer.start();


    @Override
    protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(background,0,0,this);
    for(Asteroid asteroid:asteroids){
    asteroid.drawAsteroid(g);


    $ b @Override
    public Dimension getPreferredSize(){
    return new Dimension(D_W,D_H);
    }

    public class Asteroid {
    Rectangle2D rectangle;
    图片asteroidImage;
    JPanel面板;
    int x,y;

    public Asteroid(JPanel panel,Image image,int x,int y){
    this.panel = panel;
    this.asteroidImage = image;
    this.x = x;
    this.y = y;
    rectangle = new Rectangle2D.Double(
    x,y,image.getWidth(panel),image.getHeight(panel));
    }

    public void drawAsteroid(Graphics g){
    g.drawImage(asteroidImage,x,y,panel);
    }

    public void move(){
    y + = 5;



    public static void main(String [] args){
    SwingUtilities.invokeLater(new Runnable(){
    public void run ){
    JFrame frame = new JFrame();
    frame.add(new AsteroidBackground());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack() ;
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    }
    });
    }
    }


    I was programming a game similar to asteroid, but I do not understand how to spawn the asteroids in the background.

    now i spawn an asteroid in the main class but i want create a class for the asteroid ho i do it?

    MAIN CLASS

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        if(flag_img)
        {
            background(g2d);  
            logo(g2d);          
            menu(g2d);          
            spaceship(g2d);   
            crediti(g2d);    
        }
    }
    

    background function(now)

    private void background(Graphics2D g2d) 
    {
    
        asteroidi_g_x+=r.nextInt(4);
        asteroidi_g_y+=r.nextInt(1);
        g2d.drawImage(asteroidi_g[0], asteroidi_g_x,asteroidi_g_y,this);
    }
    

    background function(what i want)

    private void background(Graphics2D g2d) 
    {
        asteroid asteroid = new asteroid[10];
    }
    

    and class asteroid

    public class asteroid extends JPanel implements ActionListener
    {
       private BufferedImage images_asteroid;
       private boolean flag_img;
    
       private JPanel jp;
    
       private int x,y;
    
       public asteroide_grande(JPanel jp)
       {
        flag_img = true;
        x = (jp.getWidth()/2);
        y = (jp.getHeight()/2);
        this.jp = jp;
    
            try {
                images_asterod = ImageIO.read(this.getClass().getResource("images/asteroid/a1.png"));
            } catch(IOException e){flag = false;}
    }
    
    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
       if(flag_img)
      {
            g.drawImage(images_asteroid, 100, 100,this);
      }
    }
    
    
    @Override
    public void actionPerformed(ActionEvent e) 
    {
        x=x-1;
        y=y+1;
        repaint();
    }
    

    method paintcomponent in class doesn't work

    解决方案

    1. Don't have your Asteroid class extends JPanel. Instead have it as a class that model's asteroid data and has data manipulation methods. You'll also want to have a draw method that take a Graphic context. Something like

      public class Asteroid {
          Image asteroidImage;
          JPanel panel;
          int x, y;
      
          public Asteroid(JPanel panel, Image image, int x, int y) {
              this.panel = panel;
              this.asteroidImage = image;
              this.x = x;
              this.y = y;
          }
      
          public void drawAsteroid(Graphics g) {
              g.drawImage(asteroidImage, x, y, panel);
          }
      
          public void move() {
              x += 5;
          }
      }
      

    2. Now you have a model of an asteroid, you can create a List of Asteriod objects and iterate through them and use it's drawAsteroid method to paint them. Something like

      public class GamePanel extends JPanel {
          List<Asteroid> asteroids;
          Image asteroidImage;
      
          public GamePanel(){
              asteroidImage = ...
              asteroids = new ArrayList<>();
              asteroids.add(new Asteroid(GamePanel.this, asteroidImage, 100, 100));
              // add more asteriods
          }
      
          @Override
          protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              for (Asteriod asteroid: asteriods) {
                  asteriod.drawAsteroid(g);
              }
          }
      }
      

    3. To animate them, you'll want to use a javax.swing.Timer. See more at How to Use Swing Timers. You'll want to manipulate the Asteriod data in the Timer. With the code provided above, you can just call it's move method, then call repaint(). Something like

      public GamePanel(){
          ...
          Timer timer = new Timer(30, new ActionListener(){
              public void actionPerformed(ActionEvent e) {
                  Iterator it = asteroids.iterator();
                  while (it.hasNaext()) {
                      Asteroid asteriod = (Asteroid)it.next();
                      asteroid.move();
                  }
              }
          });
      }
      


    You can see a bunch more complete example of animating multiple objects here and here and here and here and here


    Here's a full example. You'll see I included a Rectangle2D object in the Astreroid class. That's just if you want to check for collision detection. You should move the Rectangle2D x and/or y with every Asreroid movement of x and y. Then you can check if asteroid.rectangle.intersects(someOtherObject)

    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Random;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.Timer;
    
    public class AsteroidBackground extends JPanel {
    
        private static final int D_W = 400;
        private static final int D_H = 600;
        BufferedImage asteroidImage;
        BufferedImage background;
        List<Asteroid> asteroids;
        Random random = new Random();
        int countToAddAsteroid = 0;
        int y;
    
        public AsteroidBackground() {
            try {
                asteroidImage = ImageIO.read(getClass().getResource("/resources/small-asteroid.png"));
                background = ImageIO.read(getClass().getResource("/resources/space.png"));
            } catch (IOException ex) {
                Logger.getLogger(AsteroidBackground.class.getName()).log(Level.SEVERE, null, ex);
            }
            asteroids = new ArrayList<>();
            y = 0 - asteroidImage.getHeight();
    
            Timer timer = new Timer(40, new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    if (countToAddAsteroid >= 25) {
                        int randX = random.nextInt(D_W);
                        asteroids.add(new Asteroid(AsteroidBackground.this, asteroidImage, randX, y));
                        countToAddAsteroid = 0;
                    }
                    countToAddAsteroid++;
                    Iterator it = asteroids.iterator();
                    while (it.hasNext()) {
                        Asteroid asteroid = (Asteroid)it.next();
                        if (asteroid.y >= D_H) {
                            it.remove();
                        } else {
                             asteroid.move();
                        } 
                    }
                    repaint();
                }
            });
            timer.start();
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(background, 0, 0, this);
            for (Asteroid asteroid : asteroids) {
                asteroid.drawAsteroid(g);
            }
        }
    
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(D_W, D_H);
        }
    
        public class Asteroid {
            Rectangle2D rectangle;
            Image asteroidImage;
            JPanel panel;
            int x, y;
    
            public Asteroid(JPanel panel, Image image, int x, int y) {
                this.panel = panel;
                this.asteroidImage = image;
                this.x = x;
                this.y = y;
                rectangle = new Rectangle2D.Double(
                        x, y, image.getWidth(panel), image.getHeight(panel));
            }
    
            public void drawAsteroid(Graphics g) {
                g.drawImage(asteroidImage, x, y, panel);
            }
    
            public void move() {
                y += 5;
            }
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame();
                    frame.add(new AsteroidBackground());
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    }
    

    这篇关于动画背景java游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆