Get the location in front of a player

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

1. PLOTARCO

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 Supporter

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.

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 x 8
• Winner x 6
• Useful x 4
• Informative x 1
3. Choco Moderator

D: I was just typing that out. I guess I was a little late to the party!

• Like x 3
• Funny x 2
• Optimistic x 1
4. redbau

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 x 1
• Friendly x 1