1
\$\begingroup\$

I am coding an Asteroids game in Java. In the real arcade game, asteroids are made of irregular shapes like this: enter image description here

When I code, I can only set asteroids to 1 or another specific shape, like this:

enter image description here

I want to make all of the asteroids in my game of totally randomly generated shapes, and I am already tired of designing specific shapes of my own. Here is a snippet of my code that generates the asteroid's shape. P.S: The image does not show it, but I am using the Polygon class and constructor which only enables me to input 2 int[]s and a number of sides.

   public void makeShape() {
    int x = (int) this.x;
    int y = (int) this.y;
    this.shape = new Polygon(new int[]{x - 15, x - 30, x - 10, x - 13, x,x + 10, x + 10}, new int[]{y - 30, y - 15, y + 5, y + 30, y + 35, y + 30, y}, 7); 
}

I have tried putting all of the variables on Math.random(), but it outputs nothing but a scribble, even if I were using the Polygon class.

\$\endgroup\$
1
\$\begingroup\$

You could let a point travel on a circle in discreet steps and adjust the radius for each step, that would make it look jagged and irregular.

Something like this might work for you:

/**
 * 
 * @param px The center X of the shape
 * @param py The center Y of the shape
 * @param numberOfNodes How many dents the shape can have. 
 * @param minRadius Radius of the deepest valley
 * @param maxRadius Radius of the tallest mountain
 * @return Some shape
 */
private Polygon makeShape(int px, int py, int numberOfNodes, double minRadius, double maxRadius) {
    // Split a full circle into numberOfNodes step, this is how much to advance each part
    double angleStep = Math.PI * 2 / numberOfNodes;
    Polygon shape = new Polygon();
    for(int i = 0; i < numberOfNodes; ++i) {
        double targetAngle = angleStep * i; // This is the angle we want if all parts are equally spaced
        double angle = targetAngle + (rnd.nextDouble() - 0.5) * angleStep * 0.25; // add a random factor to the angle, which is +- 25% of the angle step
        double radius = minRadius + rnd.nextDouble() * (maxRadius - minRadius); // make the radius random but within minRadius to maxRadius
        // calculate x and y positions of the part point
        double x = Math.cos(angle) * radius; 
        double y = Math.sin(angle) * radius;
        shape.addPoint((int)x, (int)y);
    }
    shape.translate(px, py);
    return shape;
}

px and py correspond to your this.x and this.y

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.