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

2023/5/25

Interaction between 2 characters and spawning a new one

vachiotis vachiotis

2023/5/25

#
I have a program where I want a character, lets say a male fish, interacts with a female fish and I want them to spawn another fish (either male or female, it doesnt really matter). I am new to programming and I can't find a solution to this problem. Can I get some help?
danpost danpost

2023/5/25

#
vachiotis wrote...
I have a program where I want a character, lets say a male fish, interacts with a female fish and I want them to spawn another fish (either male or female, it doesnt really matter). I am new to programming and I can't find a solution to this problem. Can I get some help?
Since your Fish objects have a "sex" state, you should have a variable for male/female:
private int sex = Greenfoot.getRandomNumber(2);
Let's say that male = 1 and female = 0. Now, you can add the following to the act method:
Fish fish = (Fish) getOneIntersectingObject(Fish.class);
if (fish != null && fish.sex+sex == 1 && Greenfoot.getRandomNumber(50) == 0) {
    int x = (fish.getX()+getX())/2;
    int y = (fish.getY()+getY())/2;
    getWorld().addObject(new Fish(), x, y);
}
I added a random chance to reproduce and placed the new fish directly between the two "parents". If the two parents intersect each other for too long, it would be possible to produce multiple new fish. If you have images that are intended for a specific sex, they can be set to the actor in a constructor of the class.
You need to login to post a reply.