Getting the block in front of a player

Discussion in 'Plugin Development' started by WarmakerT, Apr 15, 2014.

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


    I'd like to get the block that's in front of a player (in front of the feet location).
    There was a thread in 2012 about this issue but unfortunately getting the target block won't work in my situation.

    Do you guys have any idea what I could do?
  2. Offline


    Here's how I would do it. Calculate the direction from the player's Yaw value and get the block that way. Like this:
    1. int yaw = (int)player.getLocation().getYaw()+45;
    2. while(yaw<0)
    3. yaw+=360;
    4. while(yaw>360)
    5. yaw-=360;
    6. int direction = yaw/90; // this will be the same direction number that F3 mode shows
    7. Block b = player.getLocation().getBlock();
    8. switch(direction)
    9. {
    10. case 0: b=b.getRelative(BlockFace.SOUTH); break;
    11. case 1: b=b.getRelative(BlockFace.WEST); break;
    12. case 2: b=b.getRelative(BlockFace.NORTH); break;
    13. case 3: b=b.getRelative(BlockFace.EAST);
    14. }

    You could change the math so that it can get diagonals too if you need it.
    WarmakerT likes this.
  3. Offline


    St3venAU Thanks. Adding to this question: How would I get what direction a player's moving to?
  4. Offline


    If you are doing this while the player is moving, you can use the PlayerMoveEvent, and then get the difference between getFrom() and getTo() (I think the methods are called). Then, you can use a couple of trigonometric functions to get the angle at which they're actually moving, and apply the same logic as above with their head yaw.
    WarmakerT likes this.
  5. Offline


    You can also get the direction a player is moving at any time with player.getVelocity(). Again you would have to do some maths to extract a direction from the vector.
    WarmakerT likes this.
Thread Status:
Not open for further replies.

Share This Page