Getting a random block in a radius

Discussion in 'Plugin Development' started by MechanicBoii, Sep 23, 2018.

Thread Status:
Not open for further replies.
  1. Offline


    Hey guys, I wanted to get a RANDOM block from a Location.

    Thats what I got.

    When I try to do that, it sets the whole Location with TNT
  2. Offline


                       for (double x = all.getLocation().getX() - 4; x < all.getLocation().getX() + 4; x++) {
                            for (double z = all.getLocation().getZ() - 4; z < all.getLocation().getZ() + 4; z++) {
                                Location location = new Location(all.getWorld(), x, all.getLocation().getY() + 10, z);
                                Random random = new Random();
                                Block block = blocks.get(random.nextInt(blocks.size()));
                                block.getWorld().spawnEntity(block.getLocation(), EntityType.PRIMED_TNT);
    I think your issue is that you encapsulated incorrectly. Right now, you make two for loops for the X and then the Z, find a location using them, But then clear the whole blocks list every time a new one is added. That means that only the last X and Z, where they are equal to X+4 and Z+4 will be stored in the list. At the same time, For every time a location is added, you spawn another primed TNT.

    The code where you clear blocks should be above the for loop, and the for loop should only contain the blocks.add line. Then, the rest of the code for choosing a random location should be below the for loop.
  3. Offline


    Is it really important if I clear "blocks" first? I mean, the blocks from the Location get added after it got cleared, so it doesnt care, Right?
  4. Could you explain which random blocks you’re trying to get? 81 random blocks? Or one random block in a square area? If so, you can just use this:

    public int xoffset = random.nextInt(9) - 4;
    public int zoffset = random.nextInt(9) - 4;
    Block block = world.getBlock(location.getX() + xoffset, location.getY() + 10, location.getZ() + zoffset);
    //you now have a magic leprechaun at the random block
Thread Status:
Not open for further replies.

Share This Page