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

2013/11/24

Moving object to opposite of world when it reaches one side

bzhang bzhang

2013/11/24

#
I'm programming a game where the stars in the game move to the right side of the world when it reaches the left side; this is the code I have for it if(getX()<3){ setLocation(1000, Greenfoot.getRandomNumber(getY())); } After running the game for a few seconds, I get a terminal window that says java.lang.IllegalArgumentException: n must be positive. I haven't defined n anywhere and I've double checked which line of code it's referring to. Help please :(
Gevater_Tod4711 Gevater_Tod4711

2013/11/24

#
I think the problem could be that getY() sometimes returns a negative value. Greenfoot.getRandomNumber(int) needs a positive value. That probably causes the exception. If you post your code we can help you fixing this. You should also have a look at World Wrapping by SPower. I think scenario can help you.
bzhang bzhang

2013/11/24

#
private static final int SIZE = 3; private int c = Greenfoot.getRandomNumber(256); private int speed = Greenfoot.getRandomNumber(3)+3; private int x = 997; public Star() { GreenfootImage img = new GreenfootImage(SIZE,SIZE); img.setColor(new Color(c, c, c)); img.fillOval(0,0,SIZE,SIZE); setImage(img); } public void act() { setLocation(getX()-speed, getY()); if(getX()<3){ setLocation(x, Greenfoot.getRandomNumber(getY())); } } this is my full code for the star class
danpost danpost

2013/11/25

#
You do not want to use the current location of the object (by using 'getY') to limit the random number generation. If 'getY' returns '0' then this error will occur as no valid return value would be legal (zero is not positive). You should instead use the height of the world by using 'getHeight' (rather 'getWorld().getHeight()', since the code is in an actor class).
You need to login to post a reply.