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

2019/5/6

Actors as parameters

MRCampbell MRCampbell

2019/5/6

#
In my world I creates a number of objects randomly in the world. I am doing this for 2 different Actors in different ways, so i though a method would simplify things. However I am having trouble passing an actor as a parameter. Here is the method I have so far.
1
2
3
4
5
6
7
8
9
public void createThingsRandLocal(int num, Actor object)
    {
        for (int i = 0; i < num; i = i + 1)
        {
            int xSpawn = Greenfoot.getRandomNumber(600);
            int ySpawn = Greenfoot.getRandomNumber(400);
            addObject(object, xSpawn, ySpawn);
        }
    }
Here I call the method.
1
createThingsRandLocal(100, Food)
danpost danpost

2019/5/6

#
Move the for loop outside the method so the method can add a single object at a time: Use:
1
2
3
4
5
6
public void addRandomLocal(Actor object)
{
    int xSpawn = Greenfoot.getRandomNumber(600);
    int ySpawn = Greenfoot.getRandomNumber(400);
    addObject(object, xSpawn, ySpawn);
}
and call it with:
1
for (int i=0; i<100; i++) addRandomLocal(new Food());
MRCampbell MRCampbell

2019/5/6

#
Thanks. Is there any way to keep the loop inside the method? Or a reason why it should not?
danpost danpost

2019/5/6

#
MRCampbell wrote...
Is there any way to keep the loop inside the method?
You could, if you made the method specifically for one type object:
1
2
3
4
5
6
7
8
9
public void addRandomFood(int num)
{
    for (int i=0; i<num; i++)
    {
        int xSpawn = Greenfoot.getRandomNumber(600);
        int ySpawn = Greenfoot.getRandomNumber(400);
        addObject(new Food(), xSpawn, ySpawn);
    }
}
Also what if my object constructor has a parameter?
What is the parameter for and how is it used?
MRCampbell MRCampbell

2019/5/9

#
Thanks for your help. Can you explain what limitations in java won't allow me to add an object inside the loop with a parameter?
Super_Hippo Super_Hippo

2019/5/9

#
If you have an actor as the parameter, then you would add this actor several times. An actor can only be in a world at one position at a time. You don't want to add one object several times, you want to add several objects of a class.
You need to login to post a reply.