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

2014/4/25

Getkey fail

kasperk22 kasperk22

2014/4/25

#
Hey guys.. in my code i have two getKey commands... But it's only the first one that is being used. So the second getKey command does not work. However, if i delete the first getKey command, the other one works.. Here's my code:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Skydemand here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Skydemand extends SmoothMover
{
    int change = 0;
    /**
     * Act - do whatever the Skydemand wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        moving();
        shooting();
    }    
    /**
     * moving the object
     */
    private void moving()
    {
        if (Greenfoot.isKeyDown("d")) change++;  
        
        if (Greenfoot.isKeyDown("a")) change--; 
        
        if("w".equals(Greenfoot.getKey()))
        { 
            change=change+180;
        }
        
        setRotation(change);  
        setLocation(getWorld().getWidth()/2, getWorld().getHeight()/2);  
        move(65);
    }
    private void shooting()
    {
         if("space".equals(Greenfoot.getKey()))
        {
            fire();
        }
    }
    /**
     * Fire the cannon
     */
    private void fire()
    {
        Bullet bullet = new Bullet();
        getWorld().addObject(bullet,getX(),getY());
        bullet.setRotation(getRotation());
        bullet.move(40.0);
    }
}
erdelf erdelf

2014/4/25

#
getKey returns the last Key pressed since the last call of the method save it in a variable and then u can use it two times
danpost danpost

2014/4/25

#
The 'getKey' method works like a keyboard buffer. Once a key is returned, the pointer moves to the next key; so, you will never get the same keystroke twice. Solution, check for both keystrokes within the same method and use a local variable to hold the value returned from 'getKey' so you can check it with both test values:
private void checkKeys()
{
    String key = Greenfoot.getKey();
    if ("w".equals(key)) { ... }
    if ("space".equals(key)) { ... }
}
kasperk22 kasperk22

2014/4/25

#
oh.. i fixed it now.. thanks for your replies :)
danpost danpost

2014/4/25

#
No. That is not what I wrote. Your line 28 does not look like my line 4; and your line 24 does not look like my line 5. EDIT: posted before seeing your final post.
You need to login to post a reply.