javafor-loopminecraftminecraft-forge

Minecraft getClickedPos().GetY() is read as zero only in first statement of for loop, among other things


I'm trying to make an item in Minecraft that detects a block to a maximum of six blocks beneath the block selected with said item. So, if a block that is right-clicked with the item in hand has a Y-Level of 70, it should look through all blocks directly below it until Y-Level 64, check if the needed block is there, then continue with the script. But for some reason, the positionClicked.getY() in the first statement of the for loop is read as zero, and it seems to add six instead of subtract six to the value (as in it checks up to positive 6 Y-level instead of subtracting to negative 6). Be warned, my only scripting knowledge is with LUA and a minecraft modding tutorial. Here's my code:

BlockPos positionClicked = pContext.getClickedPos();
Player player = pContext.getPlayer();
boolean foundBlock = false;

for (int i = positionClicked.getY() - 6; i <= positionClicked.getY(); i++) {
    BlockState state = pContext.getLevel().getBlockState(positionClicked.below(i));

    if(isDirtBlock(state)) {
        outputDirtBlockCoordinates(positionClicked.below(i), player, state.getBlock());
        foundBlock = true;

        break;
    }
}

I'll try to provide a clearer explanation if asked for.


Solution

  • The reason that you're always getting 0 is because you got some of your math incorrect.

    The problem is here:

    for (int i = positionClicked.getY() - 6; i <= positionClicked.getY(); i++) {
        BlockState state = pContext.getLevel().getBlockState(positionClicked.below(i));
    

    i is being set to the Y position clicked, subtracting 6 (from 70 that's 64). The second line is getting the block i blocks below the clicked position. So it's getting the blocks at y=6,5,4... all the way to 0.

    The way I would fix this is to make the for loop iterate by initializing i as 0, condition is i < 6, and keep incrementing i using i++.