Get Blocks Between Player and Block?

Discussion in 'Spigot Plugin Development' started by Heretere, Jun 30, 2016.

  1. Hey, I can't seem to figure out how I would get the blocks between the player and the block. I know I could use Player#getLineOfSight(), but that can be inconsistent if a player is derping. Is there a way I could get the location of the block then get the location of the player then just get the blocks between it?

    When I say derping I mean when a player moves their mouse around really fast and/or clicking.
    #1 Heretere, Jun 30, 2016
    Last edited: Jun 30, 2016
  2. Choco


    What do you mean by, "if a player is derping"? As in their head is backwards? I believe that's just a client-side glitch that wouldn't affect that method
    • Agree Agree x 2
  3. You could do a (nested) for loop.
  4. No, I mean like if they are moving their mouse around a lot and randomly clicking.

    How would a nested for loop solve my problem?
  5. Well, first you would need to work out which of each x, y, and z are larger and then loop from the smaller of each to the larger of each and get the block at that x, y, z.

    Is that not good? What exactly are you trying to do?
  6. Basically I want to do what Player#getLineOfSight() does just without depending on pitch/yaw and depending on the locations. So the method would be like:
    Code (Text):
    getBlocksBetween(Location loc1, Location loc2) {
    //What I am trying to figure out
    In this case the first location would be player#getHeadLocation() and the second location would be the Block#getLocation()
  7. Your best bet is listening for the PlayerMoveEvent and checking the new location's yaw/pitch - there aren't any better values.
  8. Choco

    Moderator, org.bukkit.util.Vector, double, int)
    This is what you want
    • Agree Agree x 1
  9. @megamichiel
    Turns out block iterator wasn't working for me so I decided to sit down and focus and I created this method which so far, seems to be doing what I want.
    Code (Text):
        public static List<Block> getBlocksInLine(Location loc1, Location loc2) {
            List<Block> blocks = new ArrayList<>();
            int distance = (int) Math.ceil(loc1.distance(loc2));
            Vector direction = loc2.toVector().subtract(loc1.toVector());
            direction.setX(Math.ceil((direction.getX() / distance) * 100D) / 100D).setY(direction.getY() / distance).setZ(Math.ceil((direction.getZ() / distance) * 100D) / 100D);
            Vector vec1 = loc1.toVector();
            for (int x = 0; x <= distance; x++) {
                Block b = vec1.add(direction).toLocation(loc1.getWorld()).getBlock();
                if (b.equals(loc2.getBlock())) {
            return blocks;