Hi I'm trying to make a screen that will have a bunch of platforms that will place themselves randomly around a JFrame. I know how to do the stuff to make the character jump and to deal with the collisions just not a way to place the platforms on the screen randomly so they are close enough together that the character could reach. Any help is appreciated.


Think of the problem in reverse. Instead of creating platforms that are randomly placed and then making sure they are withing jumping range of the player, instead create the platforms at the maximum jumping range of the player and then move them randomly. So long as all your random movements are done towards the player you are guaranteed that they will be in range.


Well it's not very well defined what kind of physics etc you have in your game. If the placement of the platform should simply be a random angle and a random distance below maxDistance, something like this could work:

     * Method that returns a 2D-coordinate, at a random angle and position relative to currentPosition.
     * The distance from the returned coordinate to the currentPosition is capped by maxDistance. 
     * @param currentPosition - A double[] array of length 2, with the first element containing the x-coordinate and the second element containing the y-coordinate.
     * @param maxDistance - Maximum distance from currentPosition to the returned coordinate.
     * @return - A double[] array containing the generated random coordinates, with the first element containing the x-coordinate and the second element containing the y-coordinate. 
    private double[] setRandomPoint(double[] currentPosition, double maxDistance){
        Random r = new Random();
        double distance = maxDistance * r.nextDouble(); // A random distance, capped at maxDistance.
        double angle = 2 * Math.PI * r.nextDouble(); // A random angle.
        double[] returnVector = new double[2];
        returnVector[0] = Math.cos(angle) * distance + currentPosition[0];
        returnVector[1] = Math.sin(angle) * distance + currentPosition[1];
        return returnVector;        

However, I would assume you want a more complicated allowed placement of the platform, given that you seem to have some gravity - lower platforms are likely allowed to be further away from the currentPosition. This would require knowledge of the physics that you have implemented. You could possibly use the method above and simply set the maxDistance to the "minimum maximum distance" that you allow, maybe the maximum distance you have when the platform is straight up from the currentPosition?

Another way to solve it would be to make a bunch of allowed platform locations and pick one of those at random.


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