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

2017/6/8

How do I get two shooters working at once?

frankiegc28 frankiegc28

2017/6/8

#
I have two actors (red and blue) that are both supposed to shoot objects from the top of the screen downwards. Only one of these objects will work at a time. The red one will not shoot unless I do not add the blue shooter to the world. Is there any way to get two shooting actors working at the same time Thanks in advance!
Super_Hippo Super_Hippo

2017/6/8

#
Show the code, so we can see what is preventing the second one from shooting.
frankiegc28 frankiegc28

2017/6/8

#
Code for blue shooter:
if ("o".equals(Greenfoot.getKey()))
        {
            BlueBlob blob = new BlueBlob();
            getWorld().addObject(blob, getX(),15);
        }
Code for red shooter:
 if ("w".equals(Greenfoot.getKey()))
        {
            RedBlob blob = new RedBlob();
            getWorld().addObject(blob, getX(),15);
        }
Cod for red and blue blobs:
public void act() 
    {
        setLocation(getX(),getY()+5);
        if(atWorldEdge())
        {
            getWorld().removeObject(this);
        }
    }    
    public boolean atWorldEdge()
    {
        if(getY() > getWorld().getHeight() - 20)
            return true;
        else
            return false;
    }
Super_Hippo Super_Hippo

2017/6/8

#
The problem lies in the use of the getKey method. It should only be used to get key import for writing text. To detect a key press as a condition for anything else, use the isKeyDown method. To prevent shooting every act cycle (which will by the way also happen with getKey if you hold the key for a while), you can either have a timer variable or a boolean which tracks the current state and you only add a blob if it changes from key-not-down to key-down (if this is wanted). In either way, you have a second condition for spawning a blob.
frankiegc28 frankiegc28

2017/6/8

#
Thank You!
You need to login to post a reply.