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

2022/2/2

laser collision detection not removing the laser when a hit is detected

roonie01 roonie01

2022/2/2

#
senario is posted on my wall with source code for easy editing and to see what i mean
Spock47 Spock47

2022/2/2

#
public class Laser extends Rocket
{
    /**
     * Act - do whatever the Laser wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    int counter; 
    public void act()
    {
        // Add your action code here.
        counter++;

        // use counter to add a delay 
        if (counter>=5)
        {
            //tells the bullet class to wait until counter is equal to 5 
            setLocation (getX(),getY()-1);
            
        

        }
        else if(this.isAtEdge() ) 
        {
            getWorld().removeObject(this);   
        }
        else if (this.isTouching(enemy1.class))
        {
            getWorld().removeObject(this);   
        }
    }
}
The act method is called often (e.g. like 60 times a second). Your act method increases the counter at every call. This means that after 5 calls, the counter will be >= 5. As soon as this condition is met, only the if-block will be executed, but never the two else-blocks. That's why (after a fraction of a second) there will never be any check for removing the laser. One solution can be to remove the first "else" (line 22). That way, the check for removal will be done at any call of the act-method and not only in the first 4 calls. Live long and prosper, Spock47
You need to login to post a reply.