0

I am very new to Java but I have been working on a scrolling background game, like Geometry Dash. It is very bare bones with just some clouds to indicate that the background is moving, but I am now confronted with the problem of making it so my player can jump up then fall back down by pressing the arrow up key, like a jumping motion. I hope there is a simple solution to my problem, so that someone can help me and I understand it. I have made it so the player can jump up, but I have not been able to make it go back down after it jumps. Any help would be greatly appreciated. Thanks!

here is the code:

/*
 * 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                   
}
Sam Kin
  • 11
  • 5
  • 1
    Unfortunately there really isn't a "simple" way to make a game, in any language. In Java, [large](http://jogamp.org/jogl/www/) [complicated](https://www.lwjgl.org/) libraries are dedicated to this. And even just using Swing for time critical applications [isn't easy.](https://pavelfatin.com/low-latency-painting-in-awt-and-swing/) – markspace Jan 20 '19 at 21:05
  • "In theory", you have a vertical speed (upwards) and gravity (downwards), each update cycle, you need to be subtracting gravity away from the vertical speed until the character returns to the ground (or reaches terminal velocity). Of course, you can make all those values up, it's just simple way of providing "names" to those values. [For example](https://stackoverflow.com/questions/16493809/how-to-make-sprite-jump-in-java/16494178#16494178) and [example](https://stackoverflow.com/questions/19626338/japplet-creates-a-ball-that-bounces-and-gets-progressively-less-high-in-java/19626396#19626396) – MadProgrammer Jan 20 '19 at 21:23

1 Answers1

0

The simplest way to do this is to make the character go up, and then go down after a certain time. To do this replace the addKeyListener code in your function with the following:

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;
        }
    }
});

This uses java.util.TimerTask, which allows you to delay an action.

Hisham Hijjawi
  • 1,803
  • 2
  • 17
  • 27
  • Hmm, i tried this and im not sure this is what im looking for. I now can move up or down, but what I was looking for was to only be able to go up, and then fall back down to the previous position(think gravity). Would I be able to use this for that purpose? Thanks. – Sam Kin Jan 21 '19 at 04:05
  • It is still going back down really quickly, is there something I could change to make it go back down slower? – Sam Kin Jan 21 '19 at 04:46