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

2016/3/1

Randomise actor size

khoalabear khoalabear

2016/3/1

#
How can I randomise the size of my actors when they are spawned in to the world?
Super_Hippo Super_Hippo

2016/3/1

#
Add a constructor:
1
2
3
4
5
6
7
public NameOfTheClass()
{
    GreenfootImage img = new GreenfootImage("nameOfTheImage.png");
    double scaleFactor = (Greenfoot.getRandomNumber(40)+1) / 10; //random number between 0.1 and 4.0
    img.scale( (int)(img.getWidth()*scaleFactor), (int)(img.getHeight()*scaleFactor));
    setImage(img);
}
This should randomizes the size in a range of 10% - 400% of the original size. Of course you can change the values.
khoalabear khoalabear

2016/3/1

#
ok I stuck that into my code and I get this error. java.lang.IllegalArgumentException: Width (0) and height (0) cannot be <= 0 at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:1016) at java.awt.GraphicsConfiguration.createCompatibleImage(GraphicsConfiguration.java:186) at greenfoot.util.GraphicsUtilities.createCompatibleTranslucentImage(GraphicsUtilities.java:189) at greenfoot.GreenfootImage.scale(GreenfootImage.java:390) at AI_right.<init>(AI_right.java:34) at Pond_world.Right_spawn(Pond_world.java:46) at Pond_world.act(Pond_world.java:21) at greenfoot.core.Simulation.actWorld(Simulation.java:600) at greenfoot.core.Simulation.runOneLoop(Simulation.java:535) at greenfoot.core.Simulation.runContent(Simulation.java:215) at greenfoot.core.Simulation.run(Simulation.java:205)
Super_Hippo Super_Hippo

2016/3/2

#
That means that scaleFactor multiplied with the width or the height of the image was less than 1. What is the size of the original image and in what range should it be randomized?
khoalabear khoalabear

2016/3/2

#
the size is 182 x 145. I think I may just try and use a larger image and scale it down as it becomes pixelated when the image is scaled up.
MY BIG PLUMS
krekraw krekraw

2016/3/2

#
I disagree with rosen completely on that one
JOSHIEWOSHIE44 JOSHIEWOSHIE44

2016/3/2

#
rosen that is out matey..
Super_Hippo Super_Hippo

2016/3/2

#
Change the 10 in line 4 in my last code to 10.0, so the line looks like this:
1
double scaleFactor = (Greenfoot.getRandomNumber(40)+1) / 10.0;
Just tested it out. Because numerator and denominator both are ints, the fraction was an int as well. Now that 10.0 is a double, the fraction is also a double. So scaleFactor can't be 0 anymore.
khoalabear khoalabear

2016/3/2

#
Thanks. It's working now.
You need to login to post a reply.