首页 > 解决方案 > 如何在 Java 中为滚动游戏制作简单的跳跃动画?

问题描述

我对 Java 很陌生,但我一直在研究滚动背景游戏,比如 Geometry Dash。这是非常简单的骨架,只有一些云表示背景正在移动,但我现在面临的问题是如何制作它,以便我的玩家可以通过按向上箭头键跳起来然后回落,就像跳跃动作一样。我希望有一个简单的解决方案来解决我的问题,以便有人可以帮助我并且我理解它。我已经做到了,所以玩家可以跳起来,但我无法让它在它跳下来后返回。任何帮助将不胜感激。谢谢!

这是代码:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;


/**
 *
 * @author kids
 */
public class game extends javax.swing.JFrame {
private PaintSurface canvas;
    int x_position = 0;
    int y_position = 580;
    int x_speed = 7;
    int enemy_posX = 0;
    int enemy_posY = 560;
int x_pos = 0;
int y_pos = 0;
int x_pos2 = -1200;
int x_position2 = -1200;
int enemy_posX2 = -1150;
int enemy_posY2 = 560;
int cloudOnex = 30;
int cloudOney = 70;
int cloud2x = -1150;
int cloud2y = 70;
int cloud3x = 700;
int cloud3y = 70;
int cloud4x = -600;
int cloud4y = 70;
int playerx =400;
int playery = 540;
    /**
     * Creates new form game
     */
    public game() {

          JPanel btnPanel = new JPanel(new FlowLayout());

        JButton btnUp = new JButton("Move Up ");
        btnPanel.add(btnUp);
        btnUp.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                playery += 10;

                canvas.repaint();
                requestFocus(); // change the focus to JFrame to receive KeyEvent
            }
        });


        Container cp = getContentPane();

        cp.setLayout(new BorderLayout());

        // "super" JFrame fires KeyEvent
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent evt) {

                switch (evt.getKeyCode()) {

                    case KeyEvent.VK_UP:
                        playery -= 22;
                        repaint();
                        break;




                }
            }
        });

 this.setTitle("Scrolling Game");
        this.setSize(1200, 650);
        // super.setBackground(Color.YELLOW);
        this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
        this.add(new PaintSurface(), BorderLayout.CENTER);
        this.setVisible(true);
        canvas = new PaintSurface();
        this.add(canvas, BorderLayout.CENTER);




        //settings for the form, handling things such as exiting and size
        Timer timer = new Timer(10, e -> {
            canvas.movement();
           canvas.check();
            canvas.repaint();
        });
        timer.start();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        



     class PaintSurface extends JComponent {

        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2 = (Graphics2D) g;

            Rectangle2D background = new Rectangle2D.Float(x_pos, y_pos, 1200, 650);
            g2.setColor(Color.CYAN);
            g2.fill(background);

            Rectangle2D ground = new Rectangle2D.Float(x_position, y_position, 1200, 30);
            g2.setColor(Color.GREEN);
            g2.fill(ground);

            Rectangle2D cloudOne = new Rectangle2D.Float(cloudOnex, cloudOney, 70, 70);
            g2.setColor(Color.WHITE);
            g2.fill(cloudOne);

             Rectangle2D cloudThree = new Rectangle2D.Float(cloud3x, cloud3y, 70, 70);
            g2.setColor(Color.WHITE);
            g2.fill(cloudThree);





            Rectangle2D background2 = new Rectangle2D.Float(x_pos2, y_pos, 1200, 650);
            g2.setColor(Color.CYAN);
            g2.fill(background2);

            Rectangle2D ground2 = new Rectangle2D.Float(x_position2, y_position, 1200, 30);
            g2.setColor(Color.GREEN);
            g2.fill(ground2);

           Rectangle2D cloudTwo = new Rectangle2D.Float(cloud2x, cloud2y, 70, 70);
            g2.setColor(Color.WHITE);
            g2.fill(cloudTwo);

             Rectangle2D cloudFour = new Rectangle2D.Float(cloud4x, cloud4y, 70, 70);
            g2.setColor(Color.WHITE);
            g2.fill(cloudFour);

            Rectangle2D player = new Rectangle2D.Float(playerx, playery,40,40);
            g2.setColor(Color.red);
            g2.fill(player);


            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        /**
         * @param args the command line arguments
         */
    }

      public void movement(){

          cloudOnex += 10;
          cloud2x += 10;
          cloud3x += 10;
          cloud4x += 10;
          x_position += 10;
          x_pos += 10;
          x_position2 += 10;
          x_pos2 += 10;
          enemy_posX += 10;
          enemy_posX2 += 10;



                 try { Thread.sleep(20); }   /* this will pause for 50 milliseconds */
                 catch (InterruptedException e) { System.err.println("sleep exception"); }


        }
 public void check(){
             if (x_pos == 1200 ) {
                x_pos = -1200;
                //x_position = -1200;
                repaint();
            }
               if (x_pos2 == 1200) {
                   x_pos2 = -1200;
                 // x_position2 = -1200;
                   repaint();

               }
               if (x_position == 1200) {
                   x_position = -1200;
                   repaint();
               }
               if (x_position2 == 1200) {
                   x_position2 = -1200;
                   repaint();

               }
               if (cloudOnex == 1200) {
                   cloudOnex = -1150;
                   repaint();

               }
               if (cloud2x == 1200){
                   cloud2x = -1150;
                   repaint();

               }
              // if (x_position2 > 1300) {
               //    x_position2 = -600;
               //    repaint();

              // }

        }



     }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new game().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    // End of variables declaration                   
}

标签: javaanimationjframe

解决方案


最简单的方法是让角色上升,然后在一定时间后下降。为此,请将函数中的 addKeyListener 代码替换为以下内容:

addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent evt) {

        switch (evt.getKeyCode()) {

            case KeyEvent.VK_UP:
                playery -= 22;
                repaint();
                new java.util.Timer().schedule(
                        new java.util.TimerTask() {
                            @Override
                            public void run() {
                                playery += 22;
                            }
                        },
                        100
                );
                break;
        }
    }
});

这使用了 java.util.TimerTask,它允许你延迟一个动作。


推荐阅读