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

2021/1/27

Random asteroids with player atraction pls!

DvAndrei18 DvAndrei18

2021/1/27

#
I make a space game and I need to have random asteroids spawning on margins and all of them fly randomly.Pls I need help!
danpost danpost

2021/1/27

#
DvAndrei18 wrote...
I make a space game and I need to have random asteroids spawning on margins and all of them fly randomly.
Length of margin is twice the sum of width plus height minus four. A random pick from length will give a single point along the margin. Converting the random value to a set of coordinates is do-able, but not a simple matter (just takes a little math knowledge).
int rand = Greenfoot.getRandomNumber(2*(getWidth()+getHeight())-4);
int x = 0, y = 0;
if (rand < getWidth()*2)
{
    x = rand%getWidth();
    y = (rand/getWidth())*(getHeight()-1);
}
else
{
    y = (rand-2*getWidth())%(getHeight()-1)+1;
    x = ((rand-2*getWidth())/(getHeight()-1))*(getWidth()-1);
}
Place asteroid at (x, y), turn toward center screen and then random turn in range less than (-45, 45 ).
You need to login to post a reply.