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

2022/2/26

The bullet hits multiple times

jdkdoen05 jdkdoen05

2022/2/26

#
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Bullet here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
  public class Bullet extends Actor
  {
    
    /**
     * Act - do whatever the Bullet wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
      {
        move(20);
        Explosion();
        if (atWorldEdge())       
        {
            this.getWorld().removeObject(this);
        }
        
      }
    }

    public boolean atWorldEdge()
    {
        if(getX() < 20 || getX() > getWorld().getWidth() - 20)
            return true;
        if(getY() < 20 || getY() > getWorld().getHeight() - 20)
            return true;
        else
            return false;
    }
    public void Explosion()
    {
        boolean kill = true;
        if(kill)
            if (isTouching(Gegner.class))
            {
                kill = false;
                //removeTouching(Gegner.class);
                Levels world = (Levels)getWorld();
                getWorld().addObject(new Splode(), getX(), getY());
                //getWorld().removeObject(this);
                Greenfoot.playSound("Explosion.mp3");
                
            }
    }
}
The bullet hits my actor multiple times, but it's not supposed to. Can you change that?
RcCookie RcCookie

2022/2/26

#
I suppose you don't want the bullet to be removed when hitting, because you have that like commented out. It you do want that, just uncomment line 48. I guess you want to save in the "kill" variable whether the bullet should kill the hit object, and it should be set to false after the first contact. But right now kill is a local variable in the "Explosion" method, meaning it's value will be forgotten whenever the method call has ended. It should instead be a global variable, which exists however long the object exists. Example:
public class Bullet extends Actor {
    int globalVar = 1;

    public void explosion() {
        int localVar = 2;
    }
}
Also, by convention method names start with a lower case letter.
danpost danpost

2022/2/26

#
I believe line 40 should be outside the method.
You need to login to post a reply.