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

2014/5/13

Actor spawning

1
2
danpost danpost

2014/5/16

#
I see the problem. The cellsize (of 5) is not accounted for. Try this:
public void addedToWorld(World world)
{
    int wide = getImage().getWidth()/5;
    int high = getImage().getHeight()/5;
    int x = 0, y = 0;
    while (!getIntersectingObjects(null).isEmpty())
    {
        x = (Greenfoot.getRandomNumber(world.getWidth()-wide)+wide/2;
        y = (Greenfoot.getRandomNumber(world.getHeight()-high)+high/2;
    }
    setLocation(x, y);
}
RPGghut RPGghut

2016/3/13

#
This would be my way to figuring it out, This script goes on the level:
import greenfoot.*;
import java.util.List;

public class level_1 extends World
{
    public List<coal> Coal;

    public level_1()
    {   
        //Setting Scene
        super(800, 600, 1);
        
        //Calling Spawn Function
        spawn_treerow();
    }
    
    public void act ()
    {
        //Checking Coal positions
        checkCoal();
    }
    
    public void spawn_treerow()
    {
       //Spawning trees (could make a for loop to make more in random positons in a row)
       addObject(new tree(), 120, 100);
       addObject(new tree(), 310, 100);
       addObject(new tree(), 500, 100);
       
       //Calling Spawn Coal (Could loop if need be)
       spawn_coal();
    }
     
    public void spawn_coal()
    {
        //Spawning coal randomly
        addObject(new coal(), RandNum(5, getWidth() - 5), RandNum(5, getHeight() - 5));
        
        //Checking Coal positions
        checkCoal();
    }
    
    public int RandNum (int start, int end)
    {
        int Random = Greenfoot.getRandomNumber(end - start + 1);
        return start + Random;
    }
    
    public void checkCoal ()
    {
        Coal = getObjects(coal.class);
        if (Coal.size() == 0)
            spawn_coal();
    }
}
and this script goes on the coal Actor:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)


public class coal extends MapObjects
{

    public void act() 
    {
        if (!getIntersectingObjects(tree.class).isEmpty())
        {
            getWorld().removeObject(this);
        }
    }    
}
I've test it out a few times and seems to work. Hope this helped.
You need to login to post a reply.
1
2