0

What's the best way I can make random obstacles come my way so my square can dodge them? Kinda like flappy bird but small box like obstacles.

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Jumpy 
extends Applet
implements KeyListener{

private Rectangle rect;

public void init()
{
    this.addKeyListener(this);

rect = new Rectangle(50, 400, 50, 50);
}

public void paint(Graphics g)
{
    setSize(500, 500);

    Graphics2D g2 = (Graphics2D)g;
    g2.fill(rect);
}

@Override
public void keyPressed(KeyEvent e) {


 if (e.getKeyCode() == KeyEvent.VK_UP)
    {
    rect.setLocation(rect.x, rect.y - 13);  
    }
     if (e.getKeyCode() == KeyEvent.VK_DOWN)
    {
    rect.setLocation(rect.x, rect.y + 13);  
    }

    repaint();


}
@Override
public void keyReleased(KeyEvent e) {               
}
@Override
public void keyTyped(KeyEvent e) {      
}}

I don't want you to write my code. I'm just asking what method/way/how would be best to make moving obstacles come my way? I'm new to java so something simple and smooth...Thanks

  • 2
    `Applet` is not Swing, it's not even a frame. Start with a `JPanel` as the base component, add your logic and rendering here, and add it to a `JFrame`. Use [key bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) instead of `KeyListener`, don't override `paint`, use `paintComponent` (if the `JPanel`) instead and don't forget to call `super.paintComponent` first. Take a look at [How to use Swing Timer](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) for ideas about how to perform animation in Swing – MadProgrammer May 12 '14 at 04:44
  • 1
    Do what MadProgrammer says, plus separate your GUI model from your GUI view. Create an Obstacle class and have your JPanel draw instances of the Obstacle class. Read my [Horse Race GUI](http://java-articles.info/articles/?p=425) article to see how to put a Java Swing GUI together with animation. – Gilbert Le Blanc May 12 '14 at 05:19
  • MadProgrammer does that mean I cant use applet? also we havent learned key bindings and I honestly dont have time to learn it, i hope this can do. –  May 14 '14 at 02:15

0 Answers0