I am getting some weird behavior when I add setBackground() to the world's constructor on line 21. Below is the code for the world and below that is the code for the only actor. Without line 21, the block bounces around and changes color as expected. With the setBackground() method on line 21, it appears that an infinite trail of blocks are added like a long snake.
Maybe I don't understand everything the setBackground() method does. Any advice would be helpful.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class MyWorld here. * * @author (your name) * @version (a version number or a date) */ public class MyWorld extends World { private GreenfootImage theBackground = new GreenfootImage(600, 400); private Block theBlock = new Block(); /** * Constructor for objects of class MyWorld. * */ public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(600, 400, 1, false); setBackground(theBackground); addObject(theBlock, 100, 100); } }
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Box here. * * @author (your name) * @version (a version number or a date) */ public class Block extends Actor { GreenfootImage theImage = new GreenfootImage(25, 25); int red = Greenfoot.getRandomNumber(256); int green = Greenfoot.getRandomNumber(256); int blue = Greenfoot.getRandomNumber(256); boolean redIncreasing = true; boolean greenIncreasing = true; boolean blueIncreasing = true; int xSpeed = Greenfoot.getRandomNumber(5) + 1; int ySpeed = Greenfoot.getRandomNumber(5) + 1; boolean shouldMove; public Block() { theImage.setColor(new Color(red, green, blue)); theImage.fill(); setImage(theImage); } /** * Act - do whatever the Box wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { changeColor(); motion(); bounce(); //getWorld().addObject(new Block(), getX(), getY()); } public void motion() { setLocation(getX() + xSpeed, getY() + ySpeed); } public void bounce() { if(getY() > getWorld().getHeight() || getY() < 0) { ySpeed = ySpeed * -1; } if(getX() > getWorld().getWidth() || getX() < 0) { xSpeed = xSpeed * -1; } } public void changeColor() { if(redIncreasing) { if(red < 255) { red = red + 1; } else { redIncreasing = false; } }else{ if(red > 0) { red = red - 1; } else { redIncreasing = true; } } if(greenIncreasing) { if(green < 255) { green = green + 1; } else { greenIncreasing = false; } }else{ if(green > 0) { green = green - 1; } else { greenIncreasing = true; } } if(blueIncreasing) { if(blue < 255) { blue = blue + 1; } else { blueIncreasing = false; } }else{ if(blue > 0) { blue = blue - 1; } else { blueIncreasing = true; } } //System.out.println(red + ", " + green + ", " + blue); theImage.setColor(new Color(red, green, blue)); theImage.fill(); setImage(theImage); } }