# Getting the block in front of a player

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

Not open for further replies.
1. Offline

### WarmakerT

I'd like to get the block that's in front of a player (in front of the feet location).

Do you guys have any idea what I could do?

#1
2. Offline

### St3venAU

Here's how I would do it. Calculate the direction from the player's Yaw value and get the block that way. Like this:
Code:java
`int yaw = (int)player.getLocation().getYaw()+45;while(yaw<0)    yaw+=360;while(yaw>360)    yaw-=360;int direction = yaw/90; // this will be the same direction number that F3 mode showsBlock b = player.getLocation().getBlock();switch(direction){    case 0: b=b.getRelative(BlockFace.SOUTH); break;    case 1: b=b.getRelative(BlockFace.WEST);  break;    case 2: b=b.getRelative(BlockFace.NORTH); break;    case 3: b=b.getRelative(BlockFace.EAST);}`

You could change the math so that it can get diagonals too if you need it.

#2
WarmakerT likes this.
3. Offline

### WarmakerT

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

#3
4. Offline

### coasterman10

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.

#4
WarmakerT likes this.
5. Offline

### St3venAU

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.

#5
WarmakerT likes this.