I am trying to get the block that I am looking at. The Sponge API documentation is outdated. Here is my code:
``
final Optional block = BlockRay.from(player).filter(BlockRay.onlyAirFilter()).end();
if (block.isPresent()) {
BlockRayHit defBlock = (BlockRayHit) block.get();
BlockType type = player.getWorld().getLocation(defBlock.getBlockPosition()).getBlock().getType();
src.sendMessage(Text.of("You are looking at a " + type.getName()));
} else {
src.sendMessage(Text.of("You are looking at the sky."));
}
``
When I run this code, I either get “minecraft:air” or the sky. From my understanding, the Air Filter was supposed to filter out air blocks. Am I mistaken?
I am having trouble with the predicate. I am new to Sponge and the concept of predicates. If you could give some advice, that would be great. The docs are a little outdated for BlockRay, so I am stuck.
A Predicate isn’t really a sponge thing, it’s part of the Java API introduced in Java 8, along with Lamdas and Method References, I think your looking for:
BlockRay ray = BlockRay.from(player).blockLimit(range).filter(hit -> { //Java 8 Lamda
Extent extent = hit.getExtent(); //Get the extent from the ray hit
Vector3i pos = hit.getBlockPosition(); //Get the block pos of the ray hit
BlockType bType = extent.getBlockType(pos); //Get the type of block at the position
return !bType.equals(BlockTypes.AIR); //If it's air, exclude, otherwise its cool
}).build();
Note: According to this, BlockRay.onlyAirFilter() really should be what your looking for, if the above code doesn’t work, try removing the ! negation from the return, otherwise you have a problem other than the filter.
There is no sound in the video unfortunately (will fix next time). There seems to be a bug where when I run the code without the ! in it, I always get Minecraft:Air, unless I am standing right next to a block. This is really weird behavior.