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

2012/3/8

script to shoot the object

brisa brisa

2012/3/8

#
i don't know how to type a script to shoot the object... help me please :o
Morran Morran

2012/3/8

#
You probably want to make a "Bullet" class... In your player's "act()" method, add this:
public void act()
{
     checkFire();
    //leave the rest of your player's act method alone
}
//after the "act()" method, add a new method:
public void checkFire()
{
   if(Greenfoot.isKeyDown("space")) {
       getWorld().addObject(new Bullet(), getX(), getY());
   }
}
The "Bullet" object's code might look like this:
public Bullet extends Actor
{
   public void act()
   {
       setLocation(getX() + speed, getY());
       checkBoundaries();
       destroyEnemies();
   }
   //we add a method "checkBoundaries()" that destroys bullets that are off screen.
   public void checkBoundaries()
   {
       if(getX() > getWorld().getWidth() - 1) 
            getWorld().removeObject(this);
       else if(getX() < 1) 
            getWorld().removeObject(this);
       if(getY() > getWorld().getHeight() - 1) 
            getWorld().removeObject(this);
       else if(getY() < 1) 
            getWorld().removeObject(this);
   }
   //"destroyEnemies()" destroys enemies.
   public void destroyEnemies()
   {
       //"Enemy" can be any class that you want the bullet to destroy. 
       Actor enemy = getOneIntersectingObject(Enemy.class);
       if(enemy != null) {
            getWorld().removeObject(enemy);
            getWorld().removeObject(this);
       }
   }

   private int speed = 10;
}
I hope that this helps. Are you from Indonesia? Wow! Greenfoot is very popular!
un4giv3n94 un4giv3n94

2014/3/13

#
hey morran the bullets fire like a machine gun how can i slow it down
Shade2400 Shade2400

2016/2/25

#
Thanks
Serthem Serthem

2016/5/8

#
this code is not working Morran
You need to login to post a reply.