Question

I am using a program called Greenfoot to do my java projects. there is two "actors" in Greenfoot that move around randomly. I would like to make it so that when one actor touches the other, it has a percent of changing the other actor to the same image. How do I accomplish this?

Was it helpful?

Solution

Are you looking for an Object Collision. If yes then please read this: http://www.greenfoot.org/doc/manual.html#collisions

OTHER TIPS

I presume you mean that you want there to be a chance of swapping the images over?

If so, you'll want to use the getIntersectingObjects() method of actor to determine if there are any other actors intersecting with this one.

If there are, you can use the getImage() / setImage() methods, also on Actor, to get the images of both the current actor and the one you're colliding with and swap them:

http://www.greenfoot.org/doc/javadoc/greenfoot/Actor.html#getImage() http://www.greenfoot.org/doc/javadoc/greenfoot/Actor.html#setImage()

As for the randomness, you'll need Greenfoot.getRandomNumber() method:

http://www.greenfoot.org/doc/javadoc/greenfoot/Greenfoot.html#getRandomNumber(int)

You can test the number returned to see if it's above (or below) a certain threshold to decide on your random result and whether you want to swap the numbers over or not.

Those are all the Greenfoot methods you should require, I'll leave the implementation as the exercise!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top