Build your scenario by implementing one powerup at a time. First add the Powerup class to your project; then start with the Speed_PU powerup. Once you got it working, add the next one -- and so on.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Starfighter here. * * @author (your name) * @version (a version number or a date) */ public class Starfighter extends Player { private final int SPEED_BOOST_TIMER = 115; private int speedBoostTimeLeft = SPEED_BOOST_TIMER; private int mySpeed; private boolean gotSpeedBoost = false; private int x; private int y; public Starfighter() { mySpeed = 5; } public void act() { checkKeys(); atWorldEdge(); stopAtWalls(); get(SpeedBoost.class); if (gotSpeedBoost) { speedBoostTimer(); } } public void checkKeys() { if ( Greenfoot.isKeyDown("left") ) { move(-5); } if ( Greenfoot.isKeyDown("right") ) { move(5); } if("space".equals(Greenfoot.getKey())) { getWorld().addObject(new Fireball(getRotation()), getX(), getY()); Greenfoot.playSound("fireball.wav"); } } public void stopAtWalls() { if(getOneIntersectingObject(Wall.class)!=null) { setLocation(x,y); } else { x = getX(); y = getY(); } } public void getSpeedBoost() { Actor actor = getOneObjectAtOffset(0, 0, SpeedBoost.class); if (actor != null) { getWorld().removeObject(actor); gotSpeedBoost = true; speed += 5; } } public void speedBoostTimer() { speedBoostTimeLeft--; if (speedBoostTimeLeft <= 0) { gotSpeedBoost = false; speed -= 5; speedboostTimeLeft = SPEED_BOOST_TIMER; } } }
getSpeedBoost();
getSpeedBoost();
getSpeedBoost();
import greenfoot.*; public class Powerup extends Actor { static final int SPEED_PU = 0, DRAG_PU = 1, AMMO_PU = 2; // add as needed static final GreenfootImage[] images = { "speedPU.png", "dragPU.png", "ammoPU.png" }; // add as needed; keep the same order as the static final int fields above int puType; // a value from the list of static final ints above int lifespan = 300; // about 5 to 6 seconds // a Powerup object can be created with 'new Powerup(Powerup.SPEED_PU)' or similar public Powerup(int type) { puType = type; setImage(images[powerup]); } public void act() { lifespan--; if (lifespan == 0) getWorld().removeObject(this); } public int getType() { return puType; } }
/** instead of */ Actor actor = getOneObjectAtOffset(0, 0, Powerup.class); if (actor != null) { getWorld().removeObject(actor); // etc. /** you would use */ Powerup pu = (Powerup)getOneObjectAtOffset(0, 0, Powerup.class); if (pu != null) int kind = pu.getType(); getWorld().removeObject(pu); if (kind == Powerup.SPEED_PU) { /** whatever */ } if (kind == Powerup.DRAG_PU) { /* whatever */ } // etc. }