This site requires JavaScript, please enable it in your browser!
Greenfoot back
BGY12C
BGY12C wrote ...

2014/2/4

Item thrwoing by pressing not holding the button

BGY12C BGY12C

2014/2/4

#
Hey everybody, we want to throw an object but it should only fly when we press the button and when you hold it it should only be thrown once. Here is our code:
    public void werfen(){
        String key = Greenfoot.getKey();
        if("q".equals(key)){
            getWorld().addObject(new Ball(), getX(), getY());
        }
    }
We are from germany: Werfen = throw Ball = ball Thanks
Gevater_Tod4711 Gevater_Tod4711

2014/2/4

#
You need to check whether the key was released after pressing it to make only one ball appear. Try it like this:
    //this variable is global so you should add it underneath the class declaration:
    private boolean keyPressed = false;

    public void werfen(){  
        if(Greenfoot.isKeyDown("p")){
            if (!keyPressed) {  
                getWorld().addObject(new Ball(), getX(), getY());
                keyPressed = true;
            }
        }  
        else {
            keyPressed = false;
        }
    }  
You need to login to post a reply.