Get the location in front of a player

Discussion in 'Spigot Plugin Development' started by PLOTARCO, Apr 27, 2017.

  1. How can I get the location from a player at his body +2 blocks (just in front of him)?
    Would be nice if sombdy. is answering
  2. NathanWolf


    Assuming you mean in the direction the player is looking, here is one approach:

    1. Get player direction: Vector direction = player.getLocation().getDirection();
    2. This is a normalized directional vector. This means it points from 0,0,0 to the direction the player is facing, and is 1 block long, no matter the angle.
    3. So, if we were to add this vector to the player's current location, Location oneBlockAway = player.getLocation().add(direction), we have the block one block in front of the player.
    4. A Vector can be multiplied to make it longer, just like multiplying a number to make it larger. So, to wrap this up, multiply the directional vector by 2 to make it 2 blocks long, then add it to the location to get the location 2 blocks away.

    Location twoBlocksAway = player.getLocation().add(player.getLocation().getDirection().multiply(2));

    You could also use player.getLineOfSight, if you'd like to check for blocks in the way. The above method will always get you two blocks forward, even if you're standing right in front of a wall.
    • Like Like x 8
    • Winner Winner x 6
    • Useful Useful x 4
    • Informative Informative x 1
  3. Choco


    D: I was just typing that out. I guess I was a little late to the party!
    • Like Like x 3
    • Funny Funny x 2
    • Optimistic Optimistic x 1
  4. This post was extremely well-written! I would like to note this is a wonderful example of not spoon-feeding, but "showing your math"! Great reply, this helped me a lot to understand a concept that I always thought should be easy. Now I see, it is! Thanks for sharing.
    • Like Like x 1
    • Friendly Friendly x 1