Jump to content

Trouble with packets 1.19


EthTDP

Recommended Posts

I have two classes for packets. One that makes an explosion happen when a button is pressed, and one that kills nearby entities when a button is pressed. Whenever I am in a singleplayer world, the packets work, it spawns explosions and it kills nearby entities, but whenever I start a server, it stops working. I am not sure what I am doing wrong, since I am new to the whole packets thing, and was wondering if anyone could help. 

Here is my explosion class:

public class CreeperExplosionC2SPacket {

    public CreeperExplosionC2SPacket() {

    }

    public CreeperExplosionC2SPacket(FriendlyByteBuf buf) {

    }

    public void toBytes(FriendlyByteBuf buf) {

    }

    public boolean handle(Supplier<NetworkEvent.Context> supplier) {
        NetworkEvent.Context context = supplier.get();
        context.enqueueWork(() -> {
            //HERE WE ARE ON THE SERVER
            ServerPlayer player = context.getSender();
            ServerLevel level = player.getLevel();

            HitResult block = player.pick(20.0D, 0.0F, false);
            HitResult fluid = player.pick(20.0D, 0.0F, true);

            BlockPos blockpos = ((BlockHitResult) block).getBlockPos();
            BlockPos fluidpos = ((BlockHitResult) fluid).getBlockPos();

                if (block.getType() == HitResult.Type.BLOCK) {
                    level.explode(player, blockpos.getX(), blockpos.getY(), blockpos.getZ(), 4.0f, Explosion.BlockInteraction.NONE);
                }

                if (fluid.getType() == HitResult.Type.BLOCK) {
                    level.explode(player, fluidpos.getX(), fluidpos.getY(), fluidpos.getZ(), 4.0f, Explosion.BlockInteraction.NONE);
                }
            });
        return true;
    }
}

Here is my "kill nearby entities" class:

public class WardenShootingC2SPacket {

    public WardenShootingC2SPacket() {

    }

    public WardenShootingC2SPacket(FriendlyByteBuf buf) {

    }

    public void toBytes(FriendlyByteBuf buf) {

    }

    public boolean handle(Supplier<NetworkEvent.Context> supplier) {
        NetworkEvent.Context context = supplier.get();
        context.enqueueWork(() -> {
            //HERE WE ARE ON THE SERVER
            ServerPlayer player = context.getSender();
            ServerLevel level = player.getLevel();

            List<LivingEntity> entities = level.getNearbyEntities(LivingEntity.class, TargetingConditions.DEFAULT, player, player.getBoundingBox().inflate(5.0D, 5.0D, 5.0D));

            double lowestDistanceSoFar = Double.MAX_VALUE;
            Entity closestEntity = null;

            for (LivingEntity entity : entities) {
                double distance = entity.getPosition(0).distanceTo(player.getPosition(0));
                if (distance < lowestDistanceSoFar) {
                    lowestDistanceSoFar = distance;
                    closestEntity = entity;
                }
            }

            Vec3 vec3 = player.position().add(0.0D, 1.65D, 0.0D);

            if (closestEntity != null) {

                Vec3 vec31 = closestEntity.getEyePosition().subtract(vec3);
                Vec3 vec32 = vec31.normalize();
                for (int i = 1; i < Mth.floor(vec31.length()) + 7; ++i) {
                    Vec3 vec33 = vec3.add(vec32.scale((double) i));
                    level.sendParticles(ParticleTypes.SONIC_BOOM, vec33.x, vec33.y, vec33.z,  1, 0.0D, 0.0D, 0.0D, 0.0D  );
                    level.playSound(player, player.blockPosition(), SoundEvents.WARDEN_SONIC_BOOM, SoundSource.PLAYERS, 1.0f, 1.0f);
                }

                closestEntity.hurt(DamageSource.sonicBoom(closestEntity), 20.0F);
            }
        });
        return true;
    }
}

Here is the class to register the packets:

public class ModMessages {
    private static SimpleChannel INSTANCE;

    private static int packetId = 0;
    private static int id() {
        return packetId++;
    }

    public static void register() {
        SimpleChannel net = NetworkRegistry.ChannelBuilder
                .named(new ResourceLocation(CustomItems.MODID, "messages"))
                .networkProtocolVersion(() -> "1.0")
                .clientAcceptedVersions(s -> true)
                .serverAcceptedVersions(s -> true)
                .simpleChannel();

        INSTANCE = net;

        net.messageBuilder(WardenShootingC2SPacket.class, id(), NetworkDirection.PLAY_TO_SERVER)
                .decoder(WardenShootingC2SPacket::new)
                .encoder(WardenShootingC2SPacket::toBytes)
                .consumerMainThread(WardenShootingC2SPacket::handle)
                .add();

        net.messageBuilder(CreeperExplosionC2SPacket.class, id(), NetworkDirection.PLAY_TO_SERVER)
                .decoder(CreeperExplosionC2SPacket::new)
                .encoder(CreeperExplosionC2SPacket::toBytes)
                .consumerMainThread(CreeperExplosionC2SPacket::handle)
                .add();
    }

    public static <MSG> void sendToServer(MSG message) {
        INSTANCE.sendToServer(message);
    }

    public static <MSG> void sendToPlayer(MSG message, ServerPlayer player) {
        INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), message);
    }
}

 

Link to comment
Share on other sites

My ModMessages.register is in my commonsetup:

@Mod.EventBusSubscriber(modid = CustomItems.MODID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class CommonModEvents {

    @SubscribeEvent
    public static void commonSetup(final FMLCommonSetupEvent event) {
        event.enqueueWork(() -> {
            ModVillagers.registerPOIs();
        });

        ModMessages.register();
    }
}

 

Link to comment
Share on other sites

No the game starts normal but if a code part with a breakpoint is execute the, it will be stopped at this breakpoint (Game freezed).

You then can continue and you know the code is called, if you repeat this for the way the Packet is called you can find the code part with the issue.
In your case you need to set a breakpoint at: Packet send -> Packet encode -> Packet decode -> Packet handle

Link to comment
Share on other sites

yeah I just noticed my problem. I checked it in a singleplayer and not a server. On the server, no breakpoints have worked, so I think the problem is that the packet is never sent.

Edited by EthTDP
Link to comment
Share on other sites

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

    • Caused by: net.minecraft.ResourceLocationException: Non [a-z0-9/._-] character in path of location: aquaticexpansion:Geo/tiamat.geo.json
    • I want to make a tree decorator that will generate a beehive under branches of my tree. I have no idea how to check for branches and make beehives generate because TreeDecorator.Context.logs() is just a block pos and i dont understand how it works. i hope ill get an answer here.
    • There's a scheme I got into where they promised to trade Bitcoin for me and take a cut as a commission. Seemed like a good idea at the time. But then, things went south real fast. They ended up transferring   $190,000 worth of my Bitcoin. I was devastated and felt completely helpless. That's when I stumbled upon the Wizard Web Recovery Tool. It was like a beacon of hope amid chaos. With this tool, I could finally start digging into what went wrong and hopefully get my Bitcoin back. Using Wizard Web was surprisingly easy. I just had to plug in some details about my Bitcoin account and let it do its thing. It started scanning the internet, looking for any clues about what happened to my Bitcoin. It felt like having a detective on my side, searching for answers. And guess what? Wizard Web found some leads. It uncovered evidence of the scheme's shady dealings and helped me track down the people responsible for losing my Bitcoin. Armed with this information, I took the case to court. After a long and hard-fought legal battle, the court ruled in my favor. The perpetrators were held accountable for their actions and faced criminal charges for their involvement in the scheme. It was a victory not just for me, but for anyone who's been taken advantage of by these kinds of scams. Thanks to Wizard Web Recovery, I was able to get justice and reclaim what was rightfully mine. It showed me that even in the face of adversity, there's always a way to fight back. And with the right tools and determination, anything is possible.   The following is the contact information for Wizard Web Recovery.   Email: wizard web recovery((@))programmer . net
    • Hello, good morning. I know some programming and I'm interested in mod creation. That's why I've decided to follow a tutorial guide on YouTube by TurtyWurty. https://www.youtube.com/watch?v=DhoX9cmAZqA&t=160s&ab_channel=TurtyWurty I've followed the tutorial perfectly. The problem is that when checking the food, the texture doesn't load for me. However, everything seems fine no matter how much I check. I'm sure it's something trivial, the problem is that I can't find it. Could you help me solve it, please? I leave a zip of my file so you can edit it freely. forge-1.20-Civicraft.rar
    • If you have nvidia graphics, it's important that you make sure Minecraft (and anything Minecraft-related) is set to prefer high performance graphics first. If you only update your AMD drivers it might fix the issue but cause severe performance loss vs Vanilla as it'll be running on the integrated graphics instead of dedicated nvidia graphics
  • Topics

×
×
  • Create New...

Important Information

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