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

2014/4/21

Detecting a certain number of hits

patrick26 patrick26

2014/4/21

#
Hi, I am trying to detect when the fireball hits the plant 5 times but am unsuccessful in doing so. Does anyone know how to do this? My code is shown below. Thanks for the help. import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Fireball here. * * @author (your name) * @version (a version number or a date) */ public class Fireball extends Actor { private static final int SPEED=7; private int a = 0; /** * Act - do whatever the Fireball wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move(SPEED); if(getX()>getWorld().getWidth()-3) { getWorld().removeObject(this); return; } Actor plant = getOneIntersectingObject(Plant.class); if(plant!=null) { getWorld().addObject(new Explosion(),getX(),getY()); a++; getWorld().removeObject(this); return; } if(a==5) { getWorld().addObject(new Hugeexplosion(),getX(),getY()); getWorld().removeObject(plant); getWorld().removeObject(this); return; } }
erdelf erdelf

2014/4/21

#
next time put your code in codes tags or use the code button below the reply box after u increase a you shouldnt remove "this", the fireball
danpost danpost

2014/4/21

#
Instead of detecting the Plant object from within the Fireball class, detect the Fireball objects from the Plant class and put the counter there (since the counter represents the 'health' of the plant). Anyways, by having it in the Fireball class as a non-static field, each fireball object set its field value to zero, increments it to one when intersection occurs, and then the fireball is removed, which makes the fireball and its fields destined for garbage collection.
You need to login to post a reply.