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

2016/4/15

Help with some programming

madarnt madarnt

2016/4/15

#
So I am working on a basic game where it is an ant vs a spider (I won't get into all the details) but I need help making it so when a key is pressed an actor (SpiderWeb) appears at another actor (Spider). Any help would be appreciated.
Super_Hippo Super_Hippo

2016/4/15

#
It can be made like this:
if (Greenfoot.isKeyDown("space"))
{
    addObject(new SpiderWeb(), getX(), getY());
}
To prevent many SpiderWebs from appearing at once, you can use a boolean to track the space key.
madarnt madarnt

2016/4/15

#
I'm getting an error with the "addObject" saying "cannot find symbol - method addObject(Web, int, int). Anything you can do to help? Oh and by the way it was actually "Web" not "SpiderWeb" my mistake.
public class Spider extends Actor
{
    public void act() 
    {
       if (Greenfoot.isKeyDown ("w"))
       move (4);
       if (Greenfoot.isKeyDown ("s"))
       move(-4);
       if (Greenfoot.isKeyDown ("a"))
       turn (-5);
       if (Greenfoot.isKeyDown ("d"))
       turn (5);
       Actor Ant1;
       Ant1 = getOneObjectAtOffset(0, 0, Ant1.class);
       if (Ant1 != null)
       {
          World world;
          world = getWorld();
          world.removeObject(Ant1);
       }
       if (Greenfoot.isKeyDown("e"))
       {
           addObject(new Web(), getX(), getY());
       }
    }    
}
danpost danpost

2016/4/15

#
There is no 'addObject' method in the Actor class API -- it is a part of the World class API. You need to execute the method on a World type object. The Actor class API has a method that returns the World object that an actor is in; it is the 'getWorld' method. You can call the 'addObject' method on that:
getWorld().addObject(new Web(), getX(), getY());
This will not work if the actor (the Spider object) is removed from the world before using it.
madarnt madarnt

2016/4/15

#
Thanks for all the help
madarnt madarnt

2016/4/15

#
I don't understand Boolean can I have help with this?
       private boolean web = true;
       if (Greenfoot.isKeyDown("e") && boolean.web = true)
       {
          getWorld().addObject(new Web(), getX(), getY());
          private boolean web = false;
       } 
danpost danpost

2016/4/15

#
The boolean is to track the state of the "e" key -- so you can detect when it is initially pressed or released:
// the boolean field
private boolean eKeyDown;

// in your code
if (eKeyDown != Greenfoot.isKeyDown("e")) // is state changing
{
    eKeyDown = !eKeyDown;  // save new state
    if (eKeyDown) // was just pressed
    {
        getWorld().addObject(new Web(), getX(), getY());
    }
}
You need to login to post a reply.