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

2020/3/8

Spawning actor instances in random locations

Happycrusher764 Happycrusher764

2020/3/8

#
IM trying to get actor instances to spawn randomly (same actor but different instance of the actor in the world). I really need help with this.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Level2 here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Level2 extends World
{
    
    /**
     * Constructor for objects of class Level2.
     * 
     */
    public Level2()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(800, 600, 1); 
        prepare();
         int a = Greenfoot.getRandomNumber(400);
         int b = Greenfoot.getRandomNumber(300);
         int c = Greenfoot.getRandomNumber(400);
         int d = Greenfoot.getRandomNumber(300);
         int e = Greenfoot.getRandomNumber(400);
         int f = Greenfoot.getRandomNumber(300);
    }
    
    /**
     * Prepare the world for the start of the program.
     * That is: create the initial objects and add them to the world.
     */
    private void prepare()
    {
        Strawberry strawberry = new Strawberry();
        addObject(strawberry,511,373);
        Strawberry strawberry2 = new Strawberry();
        addObject(strawberry2,269,425);
        Strawberry strawberry3 = new Strawberry();
        addObject(strawberry3,335,244);
        Strawberry strawberry4 = new Strawberry();
        addObject(strawberry4,716,385);
        Strawberry strawberry5 = new Strawberry();
        addObject(strawberry5,715,20);
        Strawberry strawberry6 = new Strawberry();
        addObject(strawberry6,162,170);
        Strawberry strawberry7 = new Strawberry();
        addObject(strawberry7,98,487);
    }
    
    public void act()
    {
        
        
    }
}
footpickle footpickle

2020/3/8

#
I've done this in my code with a rock, (called rocc)
getWorld().addObject(rocc = new Rocc(), Greenfoot.getRandomNumber(775), Greenfoot.getRandomNumber(575));
            
hope this helps!
footpickle footpickle

2020/3/8

#
put this in the class of whatever you want to exist
Happycrusher764 Happycrusher764

2020/3/8

#
It says GetWorld variable does not exist. Also what do I replace rocc with ? Sorry im hopeless at coding....
Happycrusher764 Happycrusher764

2020/3/8

#
ok nvm i removed the GetWorld method and just used add object and removed the Strabberry = new Strawberry to just new Strawberry and now it works! Thank you so much!
You need to login to post a reply.