Find BlockFace Player is Targeting

Discussion in 'Resources' started by mythcaptor, May 6, 2013.

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

    mythcaptor

    With player.getTargetBlock(), it's easy to find the block a player is looking at. It's less easy to find the BlockFace they're looking at. This is useful if you want to place a block where the player is looking, rather than replacing the block they're looking at.

    I developed some code to do this for one of my plugins, and I was surprised it actually worked. This is definitely an unintuitive approach to the problem, but it's actually a lot simpler than any other solution I've found, so I thought I'd share it.

    Cheers!

    Code:
    //code to find BlockFace player is looking at.
    Block target = null;
    BlockFace face = null;
    //set distance to cater to your needs
    Block b = p.getTargetBlock(null, 10);
    //mat will placed and removed briefly to check a blockface
    Material mat = Material.DIRT;
    //mat needs to be different from the target block, so if the target block is dirt, mat is set to stone instead
    if(b.getType().equals(Material.DIRT)){
      mat = Material.STONE;
    }
    BlockFace[] bfArray = {BlockFace.UP, BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.DOWN};
    //checks each BlockFace by placing block breifly. If target block changes, block face is found
    for(BlockFace bf:bfArray){
      Block block = b.getRelative(bf);
      Material type;
      Byte data;
      //check if adjacent block is not solid (prevents messing up blocks like chests)
      if(!block.getType().isSolid()){
        type = block.getType();
        data = block.getData();
        //block face check
        block.setType(mat);
        //if true, block face found
        if(p.getTargetBlock(null, 10).getType().equals(mat)){
     
          //do whatever with blockface
          target = block;
          face = bf;
     
     
        }
      //return block to original state
      block.setType(type);
      block.setData(data);
    }
    }
     
  2. Offline

    Zarius

    How about:

    Code:
    List<Block> blocks = p.getLastTwoTargetBlocks(null, 10);
    if (blocks.size() > 1) {
      face = blocks.get(1).getFace(blocks.get(0));
    }
    
    I haven't heavily tested this yet - not sure what situations in which blocks.size might not be 2 (tested it all around a single cobblestone block sitting the air and worked fine.
     
  3. Offline

    mblanchet75

    I want to try if there is a way to resolve this problem with trigonometry or eyes angle?
     
Thread Status:
Not open for further replies.

Share This Page