Posted February 22, 20187 yr Im trying to get the closest block to player, like the closest wheat and i really have no idea what im doing hear, im pretty stumped, can some one help
February 24, 20187 yr Well it first of all, you need code that checks all the block positions starting from the player position. However, note that as the distance gets farther the number of blocks required grows very large, so you will have to limit the range for checking to about 10 blocks for performance reasons. For the actually checking, you just loop through all the block locations using "for" loops for each of the x, y, and z dimensions and look for the block. Note though you need to check the distance of each of the target type blocks you find to see if you've actually found the closest. So the code would be something like this (I didn't check it, and it might need some modification, but you should get the general idea) Block targetBlock = Blocks.WHEAT; BlockPos closestPos = null; BlockPos checkPos = player.getPos(); for (int x = player.getX()-10; x < player.getX()+10; x++) { for (int y = player.getY()-10; x < player.getY()+10; y++) { for (int z = player.getZ()-10; z < player.getZ()+10; z++) { checkPos = new BlockPos(x, y, z); if (world.getBlockState(checkPos).getBlock == targetBlock} { // check if it is closer than any previously found position if (closestPos == null || player.getDistanceSq(player.getX() - checkPos.getX(), player.getY() - checkPos.getY(), player.getZ() - checkPos.getZ()) < player.getDistanceSq(player.getX() - closestPos.getX(), player.getY() - closestPos.getY(), player.getZ() - closestPos.getZ())) { closestPos = checkPos; } } } } } As you can see, it loops through all the combinations of x, y, and z within 10 blocks radius and checks if the block at that position is the type you're looking for. If it is, it checks to see if it is closer than anything else you've already found. There are actually cleverer ways of improving the performance, such as spiraling outwards and stopping at the first block found, but this is logically one of the most standard was to cover an area with a search. Edited February 24, 20187 yr by jabelar Check out my tutorials here: http://jabelarminecraft.blogspot.com/
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.