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

2018/2/13

How to make object disappear

Diactaeon Diactaeon

2018/2/13

#
In this project, I am creating a code where balls 'bounce' around the world and change color every time they bounce against the edge of the world. Every time a ball collides with another ball, one of the balls should disappear. However every time I try to run my code for that an error shows up. How can I make it so that one of the balls disappear when two balls collide?
private int imgNumber;
    /**
     * Create a ball.
     */
    public Ball(int direction) {
        setRotation(direction);
        imgNumber = 0;
    }
    /**
     * Act - do whatever the Ball wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
     collision();
     move(4);
     getWorld().showText("Colored Balls:" + Integer.toString(ballcount), getWorld().getWidth()/2, 50);
     if (isAtEdge()) {      //change color of balls when bounce agaisnt edge of world
         turn(getRotation()+Greenfoot.getRandomNumber(61)+150);
         changeImage();
        }   
     
    }
    /**
     * Change image of this ball
     */
    public void changeImage() {
        imgNumber++;
        if (imgNumber == 5) {
            imgNumber = 0;
        }
        setImage ("button-" + imgNumber + ".png");
    }
    public void collision() {
        if (canSee (Animal.class)) {
            getWorld().removeObject(this);
        }
    }
danpost danpost

2018/2/13

#
Option 1) remove the other ball with 'eat' method; Option 2) move 'collision' to end of 'act' method; Option 3) add
if (getWorld() == null) return;
after call to 'collision' in act method.
Diactaeon Diactaeon

2018/2/13

#
I tried moving 'collision' to the end of the act method and it worked Thanks!
You need to login to post a reply.