Getting three vertical blocks from a location

Discussion in 'Programming' started by lifehome, Jun 24, 2018.

  1. So from a line code of location below, it defines a location:
    Code (Text):
    Location loc = new Location(world, x, y, z);
    Location clone = loc.clone();
    However I was wondering how to correctly obtain the block of player head, feet and the block player is standing on. I have tried the following code, but it seems always getting the wrong block:
    Code (Text):
    Block head= w.getBlockAt(cloc.add(0,1,0));
    Block feet = w.getBlockAt(cloc.subtract(0,1,0));
    Block under = w.getBlockAt(cloc.subtract(0,2,0));
    What it gives was a wrong result
    Code (Text):
     loc: x#0, y#140, z#0
    head: x#0, y#141, z#0, [email protected]
    feet: x#0, y#140, z#0, [email protected]
    under: x#0, y#138, z#0, [email protected]
    Could anyone give some suggestion on this?
     
  2. FrostedSnowman

    Resource Staff

    Code (Java):
    BlockFace down = BlockFace.DOWN;
    for (int i = 0; i < 3; i++) {
         Block block = location.getBlock().getRelative(down);
         location = block.getLocation();
    }
    you could do something like this
     
    • Creative Creative x 1
  3. As you can see, your under location is one block too far on the y axis. Just substract one less block for this location and you will be good (probably)
     
    • Agree Agree x 1
  4. Thanks, however I prefer using less loops to keep the server not heavily loaded.

    Ah, I misread the subtraction, thanks for pointing out for that :D
     
  5. Location is a mutable object, meaning its values it contains can be modified. Something like Location#subtract is mutating those values and returning itself (not a new object).

    Code (Java):
    Location location = new Location(world, 0, 140, 0);

    Location head = location.add(0,1,0);
    Location feet = location.subtract(0,1,0);
    Location under = location.subtract(0,2,0);
    All 4 of these variables are now referencing the same object, and that object has a Y value of 138. So checking Y on any of those variables will yield 138.

    Code (Java):
    Location location = new Location(world, 0, 140, 0);

    Location head = location.clone().add(0,1,0);
    Location feet = location.clone();
    Location under = location.clone().subtract(0,1,0);
    Now there are 4 different objects with different Y values (other than feet being the same Y value as the original location). Changing the values of any of these objects will not effect any of the others. head has Y of 141, feet has Y of 140, and under has Y of 139.
     
    • Agree Agree x 1