Jump to content

[1.8] [SOLVED] Mod initializes twice, can't tell why


Recommended Posts

Posted

I'm making a mod which adds a single block to the game, based on the anvil. For some reason two of them are showing up in the creative inventory with the exact same name and icon. When I place them, they both have the right hitbox, but one of the blocks has the correct model and texture and the other is that purple-black cube. After experimenting for a bit I put a print line in my init() method and discovered that it printed twice. My conclusion is that my mod is initializing twice... for some reason... But I need it to only initialize once.

 

This code is WIP, I haven't done very much yet.

 

 

Main class

public class ExampleMod
{
    public static final String MODID = "eternalanvils";
    public static final String VERSION = "1.0";

    public static Block eternalanvil;

    @EventHandler
    public void preInit(FMLPreInitializationEvent event){
    }

    @EventHandler
    public void init(FMLInitializationEvent event)
    {

        eternalanvil = new BlockEternalAnvil();
        System.out.println("PRINTING LOOK LOOK LOOK LOOK LOOK LOOK!!!!!!!!");

        if(event.getSide() == Side.CLIENT)
        {

            Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(eternalanvil), 0, new ModelResourceLocation("eternalanvils:" + ((BlockEternalAnvil) eternalanvil).getName(), "inventory"));

        }

    }

    @Mod.EventHandler
    public void postInit(FMLPostInitializationEvent event){

    }
}

 

Block class

public class BlockEternalAnvil extends BlockFalling {

    private String name = "eternal_anvil";

    public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL);

    protected BlockEternalAnvil(){
        super(Material.anvil);
        this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH));
        this.setLightOpacity(0);
        this.setUnlocalizedName("eternalanvils_" + name);
        this.setCreativeTab(CreativeTabs.tabDecorations);
        GameRegistry.registerBlock(this, name);
    }

    public String getName(){
        return name;
    }

    public boolean isFullCube()
    {
        return false;
    }

    public boolean isOpaqueCube()
    {
        return false;
    }

    public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
    {
        EnumFacing enumfacing1 = placer.getHorizontalFacing().rotateY();
        return super.onBlockPlaced(worldIn, pos, facing, hitX, hitY, hitZ, meta, placer).withProperty(FACING, enumfacing1);
    }

    public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ)
    {
        if (!worldIn.isRemote)
        {
            playerIn.displayGui(new BlockEternalAnvil.EternalAnvil(worldIn, pos));
        }

        return true;
    }

    public void setBlockBoundsBasedOnState(IBlockAccess worldIn, BlockPos pos)
    {
        EnumFacing enumfacing = (EnumFacing)worldIn.getBlockState(pos).getValue(FACING);

        if (enumfacing.getAxis() == EnumFacing.Axis.X)
        {
            this.setBlockBounds(0.0F, 0.0F, 0.125F, 1.0F, 1.0F, 0.875F);
        }
        else
        {
            this.setBlockBounds(0.125F, 0.0F, 0.0F, 0.875F, 1.0F, 1.0F);
        }
    }

    protected void onStartFalling(EntityFallingBlock fallingEntity)
    {
        fallingEntity.setHurtEntities(true);
    }

    public void onEndFalling(World worldIn, BlockPos pos)
    {
        worldIn.playAuxSFX(1022, pos, 0);
    }

    @SideOnly(Side.CLIENT)
    public boolean shouldSideBeRendered(IBlockAccess worldIn, BlockPos pos, EnumFacing side)
    {
        return true;
    }

    /**
     * Convert the given metadata into a BlockState for this Block
     */
    public IBlockState getStateFromMeta(int meta)
    {
        return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(meta & 3));
    }

    /**
     * Possibly modify the given BlockState before rendering it on an Entity (Minecarts, Endermen, ...)
     */
    @SideOnly(Side.CLIENT)
    public IBlockState getStateForEntityRender(IBlockState state)
    {
        return this.getDefaultState().withProperty(FACING, EnumFacing.SOUTH);
    }

    /**
     * Convert the BlockState into the correct metadata value
     */
    public int getMetaFromState(IBlockState state)
    {
        byte b0 = 0;
        int i = b0 | ((EnumFacing)state.getValue(FACING)).getHorizontalIndex();
        return i;
    }

    protected BlockState createBlockState()
    {
        return new BlockState(this, new IProperty[] {FACING});
    }

    public static class EternalAnvil implements IInteractionObject
    {
        private final World world;
        private final BlockPos position;

        public EternalAnvil(World worldIn, BlockPos pos)
        {
            this.world = worldIn;
            this.position = pos;
        }

        /**
         * Gets the name of this command sender (usually username, but possibly "Rcon")
         */
        public String getName()
        {
            return "eternal_anvil";
        }

        /**
         * Returns true if this thing is named
         */
        public boolean hasCustomName()
        {
            return false;
        }

        public IChatComponent getDisplayName()
        {
            return new ChatComponentTranslation(Blocks.anvil.getUnlocalizedName() + ".name", new Object[0]);
        }

        public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn)
        {
            return new ContainerRepair(playerInventory, this.world, this.position, playerIn);
        }

        public String getGuiID()
        {
            return "minecraft:anvil";
        }
    }

}

Posted

You should really handle the FML loading events with a "proxy" system. I'm not certain that checking the side the way you do would really control it. Also, where do you even register your item?

 

Anyway, of course the init() method is going to print twice because it is called on both client and server side. You should see in the console that one print statement comes from the server, and one from the client. That is why you tried to put code to check for client (after your print statement) because otherwise all that code would run twice too.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

You should really handle the FML loading events with a "proxy" system. I'm not certain that checking the side the way you do would really control it. Also, where do you even register your item?

 

Anyway, of course the init() method is going to print twice because it is called on both client and server side. You should see in the console that one print statement comes from the server, and one from the client. That is why you tried to put code to check for client (after your print statement) because otherwise all that code would run twice too.

 

Please forgive my ignorance, my understanding of how Forge works is almost nil.

 

I put the print inside if(event.getSide() == Side.CLIENT){} and tried it with both Side.CLIENT and Side.SERVER, and it did print twice in both cases. The only other way I know how to check the side is world.isRemote(), and I don't think I have a world to check that with in init().

 

I've read a little about proxies before but I don't quite understand them. It seemed like they were for organization when you're initializing lots of blocks, items, renderers, etc., but since my mod only works with one block I didn't think it was necessary.

 

I didn't register an item anywhere because last time I made a mod which added blocks I didn't have to. I just registered the blocks and they came with item forms. I also made the item json, which is being used correctly, so again I haven't seen a need to register an item.

 

My guess is that whoever reads this will be fuming at my terrible ignorance and incompetence. I really want to learn to do this better, so if you're choosing between scolding me and giving up on me please choose to scold me instead. I promise I am not set on any of my ways if there's a better way out there.

Posted

Can we see the exact console output in a pastebin? While I agree with diesieben that the code should run once, I suspect it might be because you use System.out.println instead of a logger that the message gets logged twice.

Posted

Please forgive my ignorance, my understanding of how Forge works is almost nil.

In that case, each mystery concept should prompt you to do a Google search of this forum to do some serious reading (the forum's own search function tends to bury you in haystacks of crash reports that are not helpful, so use a smarter external search engine).

 

Read about proxies. Research side-only versus isRemote as they pertain to the dev environment versus client-server. Find out why custom resource location is better than the mesher.

 

I put the print inside if(event.getSide() == Side.CLIENT){} and tried it with both Side.CLIENT and Side.SERVER, and it did print twice in both cases.

Try running in the debugger (with a breakpoint at your print) so you can see which thread is executing each call, and so you can analyze the call stack.

 

I've read a little about proxies before but I don't quite understand them.

The proxy acts on behalf of your main mod class. "Common" proxy can be trivial because your main mod class can do common things for itself.

 

However, there are some classes won't even be loaded on a dedicated server in a true client-server installation. Just importing such a class is toxic on JVM running a server with no client. Hence the client proxy that can be loaded only in the presence of a Minecraft client. It quarantines client side-only code such as rendering and all associated graphics resources.

 

From mc 1.8 forward, proxies are essential for mods that add items (and/or blocks, since almost every block implies an item). At the very least, your client proxy will set a custom resource location for each item (don't do the mesher thing -- "why" is something else to look up).

 

I didn't register an item anywhere because last time I made a mod which added blocks I didn't have to. I just registered the blocks and they came with item forms.

In mc 1.8, I think you still get a trivial ItemBlock automatically. Beginning in (I think) mc 1.9, you must explicitly declare your own. In 1.10 I gave my mods code to replace the automatic ItemBlock for blocks that don't get non-trivial ones.

 

BTW, You should, if possible, use the latest (stable) version. Skip mc 1.8 & 1.9; go directly to 1.10.2. First, there's an expectation here that old versions have answers available in old threads we should find for ourselves. Second, working on a recent version lets you filter Google results to get recent threads, reducing the haystack.

 

Good luck!

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

Posted

I don't see why your code would run twice.

Please describe exactly how your workspace is set up.

 

I just ran the Forge setup according to instructions, so I'm not sure what kind of info you're asking for. Do you want the structure of the contents of my src folder?

 

Can we see the exact console output in a pastebin? While I agree with diesieben that the code should run once, I suspect it might be because you use System.out.println instead of a logger that the message gets logged twice.

 

Sure. This is the launcher's game output from just starting the game, not loading a world:

 

[11:13:00] [main/INFO] [LaunchWrapper]: Loading tweak class name net.minecraftforge.fml.common.launcher.FMLTweaker
[11:13:00] [main/INFO] [LaunchWrapper]: Using primary tweak class name net.minecraftforge.fml.common.launcher.FMLTweaker
[11:13:00] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.common.launcher.FMLTweaker
[11:13:00] [main/INFO] [FML]: Forge Mod Loader version 11.14.4.1563 for Minecraft 1.8 loading
[11:13:00] [main/INFO] [FML]: Java is Java HotSpot(TM) 64-Bit Server VM, version 1.8.0_25, running on Windows 10:amd64:10.0, installed at C:\Program Files (x86)\Minecraft\runtime\jre-x64\1.8.0_25
[11:13:00] [main/INFO] [LaunchWrapper]: Loading tweak class name net.minecraftforge.fml.common.launcher.FMLInjectionAndSortingTweaker
[11:13:00] [main/INFO] [LaunchWrapper]: Loading tweak class name net.minecraftforge.fml.common.launcher.FMLDeobfTweaker
[11:13:00] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.common.launcher.FMLInjectionAndSortingTweaker
[11:13:00] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.common.launcher.FMLInjectionAndSortingTweaker
[11:13:00] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.relauncher.CoreModManager$FMLPluginWrapper
[11:13:01] [main/INFO] [FML]: Found valid fingerprint for Minecraft. Certificate fingerprint cd99959656f753dc28d863b46769f7f8fbaefcfc
[11:13:01] [main/ERROR] [FML]: FML appears to be missing any signature data. This is not a good thing
[11:13:01] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.relauncher.CoreModManager$FMLPluginWrapper
[11:13:01] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.common.launcher.FMLDeobfTweaker
[11:13:02] [main/INFO] [LaunchWrapper]: Loading tweak class name net.minecraftforge.fml.common.launcher.TerminalTweaker
[11:13:02] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.common.launcher.TerminalTweaker
[11:13:02] [main/INFO] [LaunchWrapper]: Launching wrapped minecraft {net.minecraft.client.main.Main}
[11:13:02] [main/INFO] [sTDOUT]: [net.minecraft.client.main.Main:main:55]: Completely ignored arguments: [--nativeLauncherVersion, 307]
[11:13:02] [Client thread/INFO]: Setting user: 630tiger
[11:13:04] [Client thread/INFO]: LWJGL Version: 2.9.1
[11:13:04] [Client thread/INFO] [sTDOUT]: [net.minecraftforge.fml.client.SplashProgress:start:246]: ---- Minecraft Crash Report ----
// I just don't know what went wrong 

Time: 9/5/16 11:13 AM
Description: Loading screen debug info

This is just a prompt for computer specs to be printed. THIS IS NOT A ERROR


A detailed walkthrough of the error, its code path and all known details is as follows:
---------------------------------------------------------------------------------------

-- System Details --
Details:
Minecraft Version: 1.8
Operating System: Windows 10 (amd64) version 10.0
Java Version: 1.8.0_25, Oracle Corporation
Java VM Version: Java HotSpot(TM) 64-Bit Server VM (mixed mode), Oracle Corporation
Memory: 48344680 bytes (46 MB) / 194412544 bytes (185 MB) up to 3207856128 bytes (3059 MB)
JVM Flags: 6 total; -XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump -Xmx3G -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:-UseAdaptiveSizePolicy -Xmn128M
IntCache: cache: 0, tcache: 0, allocated: 0, tallocated: 0
FML: 
Loaded coremods (and transformers): 
GL info: ' Vendor: 'NVIDIA Corporation' Version: '4.5.0 NVIDIA 368.69' Renderer: 'GeForce GTX 970/PCIe/SSE2'
[11:13:04] [Client thread/INFO] [MinecraftForge]: Attempting early MinecraftForge initialization
[11:13:04] [Client thread/INFO] [FML]: MinecraftForge v11.14.4.1563 Initialized
[11:13:04] [Client thread/INFO] [FML]: Replaced 204 ore recipies
[11:13:05] [Client thread/INFO] [MinecraftForge]: Completed early MinecraftForge initialization
[11:13:05] [Client thread/INFO] [FML]: Found 0 mods from the command line. Injecting into mod discoverer
[11:13:05] [Client thread/INFO] [FML]: Searching C:\Users\ScreechingMarmot\AppData\Roaming\.minecraft\mods for mods
[11:13:05] [Client thread/INFO] [FML]: Forge Mod Loader has identified 8 mods to load
[11:13:06] [Client thread/INFO] [FML]: Attempting connection with missing mods [mcp, FML, Forge, braziermod, eternalanvils, sprintnerf, wildanimals, chiselsandbits] at CLIENT
[11:13:06] [Client thread/INFO] [FML]: Attempting connection with missing mods [mcp, FML, Forge, braziermod, eternalanvils, sprintnerf, wildanimals, chiselsandbits] at SERVER
[11:13:06] [Client thread/INFO]: Reloading ResourceManager: Default, FMLFileResourcePack:Forge Mod Loader, FMLFileResourcePack:Minecraft Forge, FMLFileResourcePack:Brazier Mod, FMLFileResourcePack:Eternal Anvils, FMLFileResourcePack:Sprint Nerf, FMLFileResourcePack:Wild Animals, FMLFileResourcePack:Chisels & Bits
[11:13:06] [Client thread/INFO] [FML]: Processing ObjectHolder annotations
[11:13:06] [Client thread/INFO] [FML]: Found 384 ObjectHolder annotations
[11:13:06] [Client thread/INFO] [FML]: Identifying ItemStackHolder annotations
[11:13:06] [Client thread/INFO] [FML]: Found 0 ItemStackHolder annotations
[11:13:06] [Client thread/INFO] [FML]: Configured a dormant chunk cache size of 0
[11:13:06] [Forge Version Check/INFO] [ForgeVersionCheck]: [Forge] Starting version check at http://files.minecraftforge.net/maven/net/minecraftforge/forge/promotions_slim.json
[11:13:06] [Forge Version Check/INFO] [ForgeVersionCheck]: [Forge] Found status: UP_TO_DATE Target: null
[11:13:07] [Client thread/INFO] [FML]: Applying holder lookups
[11:13:07] [Client thread/INFO] [FML]: Holder lookups applied
[11:13:07] [Client thread/INFO] [FML]: Injecting itemstacks
[11:13:07] [Client thread/INFO] [FML]: Itemstack injection complete
[11:13:07] [sound Library Loader/INFO]: Starting up SoundSystem...
[11:13:07] [Thread-9/INFO]: Initializing LWJGL OpenAL
[11:13:07] [Thread-9/INFO]: (The LWJGL binding of OpenAL.  For more information, see http://www.lwjgl.org)
[11:13:07] [Thread-9/INFO]: OpenAL initialized.
[11:13:07] [sound Library Loader/INFO]: Sound engine started
[11:13:08] [Client thread/INFO] [FML]: Max texture size: 16384
[11:13:08] [Client thread/INFO]: Created: 16x16 textures-atlas
[11:13:08] [Client thread/INFO] [sTDOUT]: [com.example.examplemod.ExampleMod:init:34]: PRINTING LOOK LOOK LOOK LOOK LOOK LOOK!!!!!!!!
[11:13:08] [Client thread/INFO] [sTDOUT]: [com.example.examplemod.ExampleMod:init:34]: PRINTING LOOK LOOK LOOK LOOK LOOK LOOK!!!!!!!!
[11:13:08] [Client thread/INFO] [FML]: Injecting itemstacks
[11:13:08] [Client thread/INFO] [FML]: Itemstack injection complete
[11:13:08] [Client thread/INFO] [FML]: Forge Mod Loader has successfully loaded 8 mods
[11:13:08] [Client thread/INFO]: Reloading ResourceManager: Default, FMLFileResourcePack:Forge Mod Loader, FMLFileResourcePack:Minecraft Forge, FMLFileResourcePack:Brazier Mod, FMLFileResourcePack:Eternal Anvils, FMLFileResourcePack:Sprint Nerf, FMLFileResourcePack:Wild Animals, FMLFileResourcePack:Chisels & Bits
[11:13:08] [Client thread/INFO]: SoundSystem shutting down...
[11:13:09] [Client thread/WARN]: Author: Paul Lamb, www.paulscode.com
[11:13:09] [sound Library Loader/INFO]: Starting up SoundSystem...
[11:13:09] [Thread-11/INFO]: Initializing LWJGL OpenAL
[11:13:09] [Thread-11/INFO]: (The LWJGL binding of OpenAL.  For more information, see http://www.lwjgl.org)
[11:13:09] [Thread-11/INFO]: OpenAL initialized.
[11:13:09] [sound Library Loader/INFO]: Sound engine started
[11:13:09] [Client thread/INFO] [FML]: Max texture size: 16384
[11:13:10] [Client thread/INFO]: Created: 512x512 textures-atlas
[11:13:10] [Client thread/ERROR] [FML]: Model definition for location sprintnerf:eternal_anvil#facing=north not found
[11:13:10] [Client thread/ERROR] [FML]: Model definition for location sprintnerf:eternal_anvil#facing=east not found
[11:13:10] [Client thread/ERROR] [FML]: Model definition for location sprintnerf:eternal_anvil#facing=west not found
[11:13:10] [Client thread/ERROR] [FML]: Model definition for location sprintnerf:eternal_anvil#inventory not found
[11:13:10] [Client thread/ERROR] [FML]: Model definition for location sprintnerf:eternal_anvil#facing=south not found
[11:13:40] [Client thread/INFO]: Stopping!
[11:13:40] [Client thread/INFO]: SoundSystem shutting down...
[11:13:40] [Client thread/WARN]: Author: Paul Lamb, www.paulscode.com

 

Thank you guys for helping me out.

 

@jeffryfisher, too much to quote but thank you for your response. I will read up on proxies. I'd rather not keep my mods up to date with Minecraft because... reasons that should be dealt with in a long paragraph. Basically, it sounds obnoxious to update all my mods every time, and every time a new update came out I'd have to make new mods to change/fix the new things I didn't like in addition to updating my old stuff. As it is once I make a mod for 1.8 I can just leave it there and never worry about it again, unless it needs fixing. I hadn't considered the trouble with asking for help on here though.

Posted

That console output is bizarre. One thing (might not matter): Your main class does not even have the @Mod annotation, so I can't imagine how it even gets loaded. Add the annotation to main (and make sure that no other class has one).

 

If you still have a problem after that, then go to the file system to get the log file. It has more info than the console. If it doesn't reveal the problem to you, then post it for others to see.

 

I understand the difficulty keeping up with mc updates, especially after you've made several mods. I myself abandoned 1.8.9 when I discovered that opening a 1.8 world in it would scramble all of my custom blocks. Because of the time lost, I skipped 1.9 completely so I could get a new mod in. However, having completed that mod, I'm now upgrading to the latest and will create a whole new server world when I am done.

 

Now that I know that no modded world can survive a Minecraft version change without glitching, I'll probably upgrade on alternate major releases (when my friends and I are ready for a new world).

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

Posted

That console output is bizarre. One thing (might not matter): Your main class does not even have the @Mod annotation, so I can't imagine how it even gets loaded. Add the annotation to main (and make sure that no other class has one).

 

If you still have a problem after that, then go to the file system to get the log file. It has more info than the console. If it doesn't reveal the problem to you, then post it for others to see.

 

My apologies; the main class does have @Mod, I just incorrectly assumed it wasn't important because it came before the class declaration.

 

@Mod(modid = ExampleMod.MODID, version = ExampleMod.VERSION)
public class ExampleMod
{
    public static final String MODID = "eternalanvils";
    public static final String VERSION = "1.0";

    public static Block eternalanvil;

    @EventHandler
    public void preInit(FMLPreInitializationEvent event){
    }

    @EventHandler
    public void init(FMLInitializationEvent event)
    {

        eternalanvil = new BlockEternalAnvil();
        if(event.getSide() == Side.CLIENT)
        {

            System.out.println("PRINTING LOOK LOOK LOOK LOOK LOOK LOOK!!!!!!!!");

            Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(eternalanvil), 0, new ModelResourceLocation("eternalanvils:" + ((BlockEternalAnvil) eternalanvil).getName(), "inventory"));

        }

    }

    @Mod.EventHandler
    public void postInit(FMLPostInitializationEvent event){

    }
}

 

I looked through fml-client-latest.log and... well, it looked like another one of my mods was printing the print line, which didn't make any sense. I figured out what the problem was: my current mod and that other one both used the default package "com.example.examplemod" name for their class structure.

 

*CRINGE* AAAAAGH

 

It had never occurred to me that that might be a problem but in retrospect that's probably a super basic thing and I know I've read about it before. I'll have to update my other mod now as well. But I fixed the problem with this mod! Thank you guys for bearing with me in my noobishness.

Posted

And this is why you always change that...

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.

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.