0

I want to make a game were a circle jumps over obstacles but I can't get it to jump

I've tried all keys on keyboard

import java.awt.event.KeyEvent;

public class Game {

    public static void main(String[] args) {
        StdDraw.setCanvasSize();
        circle player = new circle(0, 0.05 , 0.05) ;
        StdDraw.line(0, 0, 1, 0);       

        if(StdDraw.isKeyPressed(KeyEvent.VK_UP)){
            System.out.println("hello");
            double height = player.height;
            while(height <= 0.2)
            height = height + 0.05;

            StdDraw.setCanvasSize();
            StdDraw.line(0, 0, 1, 0);       
            StdDraw.filledCircle(0, height, 0.05);
            StdDraw.show(100);
        }
    }
}

I put in print function to test if it goes in the "if" and it doesn't

DarceVader
  • 98
  • 7
  • 1
    Possible duplicate of [How do I check if the user is pressing a key?](https://stackoverflow.com/questions/18037576/how-do-i-check-if-the-user-is-pressing-a-key) – user3486184 Jan 29 '19 at 21:21

2 Answers2

0

You aren't listening for KeyEvents the right way. The old way was to use KeyListener, and the newerish way is to use Key bindings, but for me when I was coding Java I found in terms of writing keyboard controls for games the answer was using a KeyEventDispatcher subclass, like I did here

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

i am trying to use isKeyPressed method and its just not working, is there a specific place i have to hit key?

Very likely you have to press the key while the program's GUI window has focus, but not necessarily when the mouse pointer is any particular place. But the biggest problem is timing. Your program tests whether a key is currently pressed when control reaches the if statement. That should happen extremely quickly after it first displays anything, very likely too fast for you to type, so your program flies past that before you can do anything. Furthermore, because it (very likely) responds only to keys pressed while the program's window has focus, you should not even expect to be able to preemptively press a key and have the program recognize it.

I'm not sure what the StdDraw idiom for this sort of thing would be, if there even is one. I suppose you want to create a loop that repeatedly checks for input and updates the display. Normally such a thing would run naturally on the GUI's event-dispatch thread, but StdDraw seems designed to insulate you from that.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157