How do I get the block under the player?

Viewed 2788

I want to know which block is under the Player .And if the BLock is identical to another block (selected before), do something. i tried something like this: (But I know it doesn't work at all). Thank you!

BlockPos PlayerIsStandingOn = player.getPosition().down();
Block PlayerIsStandingOnBlock = worldIn.getBlockState(PlayerIsStandingOn);
if (PlayerIsStandingOn == randomBlock) { }                              
1 Answers

You're close but getBlockState returns IBlockState not Block. You could do it like this:

BlockPos posBelow = player.getPosition().down();
IBlockState blockStateBelow = player.world.getBlockState(posBelow);

then you can either check if the block is a specific material like so, I think this is likely what you're after; this will return if the Material is not GROUND (dirt):

if(blockStateBelow.getMaterial() != Material.GROUND)
    return;
//your logic here

Or you can do a comparison to check if two blocks are the same:

if(!Block.isEqualTo(blockStateBelow.getBlock(), <your other block>))
    return;
//your logic here

And so on...

Edit

This answer was originally written for 1.12.2, it seems a few things have changed in 1.15.2

BlockPos posBelow = player.getPosition().down();
BlockState blockStateBelow = player.world.getBlockState(posBelow);
Block below = blockStateBelow.getBlock();

if(!below.equals(<your other block>))
    return;
Related