Jump to content

[Forge 1.10.2] Create a pickaxe that break unbreakable blocks?


Recommended Posts

Posted
22 hours ago, TheMasterGabriel said:

You can read about Events here on the Forge docs.

I already know that. And I am doing an pickaxe that mine 10x10 blocks. Base on the TerraPick in Botania. But I am asking how to do that (in the event). My unfinished code:

 

Spoiler

@SubscribeEvent
    public void onPlayerDig(PlayerInteractEvent event) {
        if (event.getFace() == null || event.getWorld().isRemote
                || event.getEntityPlayer().applyPlayerInteraction(event.getEntityPlayer(),
                        event.getEntityPlayer().getForward(), event.getItemStack(),
                        event.getHand()) == EnumActionResult.PASS
                || event.getEntityPlayer().getHeldItem(event.getHand()) == null
                || event.getEntityPlayer().capabilities.isCreativeMode)
            return;
        IBlockState state = event.getWorld().getBlockState(event.getPos());
        Block block = state.getBlock();

        Random random = new Random();
        if (block.getBlockHardness(state, event.getWorld(), event.getPos()) <= -1 &&
                event.getEntityPlayer().getHeldItem(event.getHand()).getItem() == LudicrousItems.infinity_pickaxe &&
                (block.getMaterial(state) == Material.ROCK || block.getMaterial(state) == Material.IRON)) {
                LudicrousItems.infinity_pickaxe.onBlockStartBreak(event.getEntityPlayer().getHeldItem(event.getHand()),
                        event.getPos(), event.getEntityPlayer());
             } else {
                ItemStack drops = block.getPickBlock(state,
                        ToolCommons.raytraceFromEntity(event.getWorld(), event.getEntityPlayer(), true, 10),
                        event.getWorld(), event.getPos(), event.getEntityPlayer());
                if (block.quantityDropped(random) == 0) {
                    if (drops == null)
                        drops = new ItemStack(block, 1, block.getMetaFromState(state));
                    dropItems(drops, event.getWorld(), event.getPos());
                } else
                    block.harvestBlock(event.getWorld(), event.getEntityPlayer(), event.getPos(), state,
                            event.getWorld().getTileEntity(event.getPos()), drops);
                event.getWorld().setBlockToAir(event.getPos());
                event.getWorld().playEvent(2001, event.getPos(),
                        Block.getIdFromBlock(block) + (block.getMetaFromState(state) << 12));
            }
        }
    }

 

Posted (edited)
12 hours ago, diesieben07 said:
  • Don't subscribe to the raw PlayerInteractEvent. Choose one of the sub-events.
  • Why are you calling applyPlayerInteraction like that? It makes no sense, you are telling the player to interact with itself. O.o
  • getForward is annotated with @SideOnly(CLIENT), which means you cannot use it in common code like this. You can learn more about sides in the documentation.
  • Why are you creating a new Random instance every time?
  • Block::getBlockHardness is deprecated, you should use IBlockState::getBlockHardness instead.
  • hardness <= -1 is not the condition for unbreakable. A block is unbreakable if it's hardness is below 0.
  • In 1.10.2 ItemStacks can still be null hence you cannot simply call getItem on the result of EntityPlayer::getHeldItem, since it might be null.
  • Block::getMaterial is deprecated, use IBlockState::getMaterial instead.
  • Why are you doing a ray-trace? You know which block was hit and you can also obtain the hit vector needed to create the RayTraceResult from the event.
  • You should not be calling quantityDropped, it is not accurate for all blocks. The only way to truly obtain a block's drops is to call Block::getDrops.
  • You should almost never call Block::getMetaFromState, especially not to construct an ItemStack.
  • Use Block.getStateId instead of manually constructing the ID from metadata.

Still doesn't work. Here is my newest code:

 

Spoiler

@SubscribeEvent
    public void onPlayerMine(PlayerInteractEvent.LeftClickBlock event) {
        if (event.getFace() == null || event.getWorld().isRemote
                || event.getEntityPlayer().getHeldItem(event.getHand()) == null
                || event.getEntityPlayer().capabilities.isCreativeMode)
            return;
        IBlockState state = event.getWorld().getBlockState(event.getPos());
        Block block = state.getBlock();
        if (state.getBlockHardness(event.getWorld(), event.getPos()) < 0 &&
                event.getEntityPlayer().getHeldItem(event.getHand()).getItem() == LudicrousItems.infinity_pickaxe &&
                (state.getMaterial() == Material.ROCK || state.getMaterial() == Material.IRON)) {
                LudicrousItems.infinity_pickaxe.onBlockStartBreak(event.getEntityPlayer().getHeldItem(event.getHand()),
                        event.getPos(), event.getEntityPlayer());
            } else {
                ItemStack drop = block.getPickBlock(state,
                        ToolHelper.raytraceFromEntity(event.getWorld(), event.getEntityPlayer(), true, 10),
                        event.getWorld(), event.getPos(), event.getEntityPlayer());
                if (block.getDrops(event.getWorld(), event.getPos(), state, EnchantmentHelper
                        .getEnchantmentLevel(Enchantments.FORTUNE,
                                new ItemStack(LudicrousItems.infinity_pickaxe))) == null) {
                    if (drop == null)
                        drop = new ItemStack(block, 1, block.getMetaFromState(state));
                    dropItems(drop, event.getWorld(), event.getPos());
                } else
                    block.harvestBlock(event.getWorld(), event.getEntityPlayer(), event.getPos(), state,
                            event.getWorld().getTileEntity(event.getPos()), drop);
                event.getWorld().setBlockToAir(event.getPos());
                event.getWorld().playEvent(2001, event.getPos(),
                        Block.getStateId(state));
            }
        }
    }

 

Edited by lethinh
Posted

Can you use the code tag please? (<>)that thing. Currently I cant even tell what you are doing

Apparently I'm addicted to these forums and can't help but read all the posts. So if I somehow help you, please click the "Like This" button, it helps.

Posted
On 23/2/2017 at 3:46 PM, CrazyGriefer1337 said:

Just try the following:

-Test if the block is unbreakable (Bedrock, or something modded)

-If yes, execute the command "fill" (Minecraft command, not Java)

-If it doesn't work, throw your PC out of the window.

This is coding not normal MC!

  • 4 weeks later...
Posted
On 27/2/2017 at 3:27 PM, diesieben07 said:
  • I am still not clear as to why you are calling onBlockStartBreak. If anything you need to completely emulate the block-breaking process as it normally occurs in PlayerInteractionManager.
  • You are still ray-tracing without the need to do that.
  • Block::getDrops will never return null.
  • You are still calling Block::getMetaFromState.

Still doesn't work!

  • 2 weeks later...
Posted

On your newest code....

  • You are comparing ItemStack instances using == which will never work.
  • Except that what you are comparing is the return of block.getItem(world, pos, state)  with the return of block.getItem(world, pos, state) (i.e.. itself) which will always be true.
On 2/27/2017 at 3:27 AM, diesieben07 said:
  • You are still calling Block::getMetaFromState.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted
22 hours ago, Draco18s said:

On your newest code....

  • You are comparing ItemStack instances using == which will never work.
  • Except that what you are comparing is the return of block.getItem(world, pos, state)  with the return of block.getItem(world, pos, state) (i.e.. itself) which will always be true.

 

Do you know how to fix those errors? I have tried all!

Posted
22 hours ago, diesieben07 said:

Please show what you tried and why it didn't work.

 

All the code that I have shown to you. And could you show me how to not call Block::getMetaFromState?

Posted (edited)
10 minutes ago, diesieben07 said:

You should not construct the dropped item stacks manually. Use Block::getDrops to obtain the drops, like I already said in my first post.

I can't. Block::getDrops is List<ItemStack> but the drop is a item stack.

Edited by lethinh
Posted
18 minutes ago, Jay Avery said:

So return a list that contains just one stack.

 

Can't be. If I do that, the method InventoryHelper::spawnItemStack and Block::harvestBlock WILL NOT WORK

Posted
1 minute ago, diesieben07 said:

What is "the drop"?

 

What? O.o

It is:

 

@SubscribeEvent
    public void onPlayerDig(PlayerInteractEvent.LeftClickBlock event) {
        World world = event.getWorld();
        EntityPlayer player = event.getEntityPlayer();

        if (event.getFace() == null || world.isRemote || StackUtils.isEmpty(player.getHeldItem(EnumHand.MAIN_HAND)) || player.isCreative())
            return;


        BlockPos pos = event.getPos();
        IBlockState state = world.getBlockState(pos);
        Block block = state.getBlock();
        List<ItemStack> drop = new ArrayList<>();
        if (block.getDrops(world, pos, state, EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, new ItemStack(this))) == drop) {
            if (drop == null)
                drop = new ArrayList<>(block.getDrops(world, pos, state, EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, new ItemStack(this))));
            InventoryHelper.spawnItemStack(world, (double) pos.getX(), (double) pos.getY(), (double) pos.getZ(), drop);
        } else
            block.harvestBlock(world, player, pos, state, world.getTileEntity(pos), drop);

        world.setBlockToAir(pos);
        world.playEvent(2001, pos, Block.getStateId(state));
    }

 

Posted

 

Quote

if (block.getDrops(world, pos, state, EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, new ItemStack(this))) == drop 

  • Now you are comparing a List<ItemStack> to an ItemStack, so the result will always be false. Why are you making this comparison anyway? What result are you actually trying to get?
  • You still keep using ==, which only checks for the exact same object, rather than for meaningfully equivalent objects. Two different ItemStacks made of the same Item and stacksize will not be equal with the == operator.
Quote

List<ItemStack> drop = new ArrayList<>()

...

if (drop == null)

  • How could drop possibly be null here after you have set it to a new ArrayList? (Hint: it couldn't).

You seem to be having trouble with some fairly fundamental Java/OOP concepts, you might be better off learning some general programming first.

 

Posted
19 hours ago, Jay Avery said:

 

  • Now you are comparing a List<ItemStack> to an ItemStack, so the result will always be false. Why are you making this comparison anyway? What result are you actually trying to get?
  • You still keep using ==, which only checks for the exact same object, rather than for meaningfully equivalent objects. Two different ItemStacks made of the same Item and stacksize will not be equal with the == operator.
  • How could drop possibly be null here after you have set it to a new ArrayList? (Hint: it couldn't).

You seem to be having trouble with some fairly fundamental Java/OOP concepts, you might be better off learning some general programming first.

 

I have just learned java for few months. And the code didn't work:

 

@SubscribeEvent
public void onPlayerDig(PlayerInteractEvent.LeftClickBlock event) {
    World world = event.getWorld();
    EntityPlayer player = event.getEntityPlayer();

    if (event.getFace() == null || world.isRemote || StackUtils.isEmpty(player.getHeldItem(EnumHand.MAIN_HAND)) || player.isCreative())
        return;

    BlockPos pos = event.getPos();
    IBlockState state = world.getBlockState(pos);
    Block block = state.getBlock();
    List<ItemStack> drop = new ArrayList<>();

    if (drop == null)
        drop = new ArrayList<>(block.getDrops(world, pos, state, EnchantmentHelper.getEnchantmentLevel(Enchantments.FORTUNE, new ItemStack(this))));

    block.harvestBlock(world, player, pos, state, world.getTileEntity(pos), new ItemStack(block));
    InventoryHelper.spawnItemStack(world, pos.getX(), pos.getY(), pos.getZ(), new ItemStack(block));

    world.setBlockToAir(pos);
    world.playEvent(2001, pos, Block.getStateId(state));
}
Posted
50 minutes ago, lethinh said:

 


    List<ItemStack> drop = new ArrayList<>();

    if (drop == null)

You're still doing this pointless check. And now you do nothing with the drop variable after you create it anyway.

 

When you say the code doesn't work, please be more specific. Exactly what does and doesn't happen, and what are you expecting to happen? At this point I've lost track of the problem.

Posted
2 hours ago, Jay Avery said:

You're still doing this pointless check. And now you do nothing with the drop variable after you create it anyway.

 

When you say the code doesn't work, please be more specific. Exactly what does and doesn't happen, and what are you expecting to happen? At this point I've lost track of the problem.

 

It doesn't break unbreakable block. That's the point of the code.

Posted
 List<ItemStack> drop = new ArrayList<>();

Cool, I have an array object

if (drop == null)

Nope, it's not null. It's an ArrayList of size zero.

block.harvestBlock(world, player, pos, state, world.getTileEntity(pos), new ItemStack(block));
InventoryHelper.spawnItemStack(world, pos.getX(), pos.getY(), pos.getZ(), new ItemStack(block));

And now, I ignore the fuck out of my array object.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted
1 hour ago, lethinh said:

 

It doesn't break unbreakable block. That's the point of the code.

Does it break ordinary breakable blocks? Does the game crash? Does the event get called?

Posted
23 hours ago, Jay Avery said:

Does it break ordinary breakable blocks? Does the game crash? Does the event get called?

It breaks ordinary breakable blocks. The game doesn't crash. And I have called the event by using MinecraftForge.EventBus::register

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
    • Do you use features of inventory profiles next (ipnext) or is there a change without it?
    • Remove rubidium - you are already using embeddium, which is a fork of rubidium
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.