Jump to content

[1.10.2] Spawning structures using Structure Blocks files


Recommended Posts

Posted

I'm wondering if there is a way to spawn a structure using the Structure Block exported file. For instance, i want to spawn this structure in my world

bwTfVdC.png

But instead of defining a class that tells block by block wich block to set in the world i want that the world generator actually "loads" the nbt files containing the structure (generated using the structure block)

For instance this file

https://mega.nz/#!1M9EEDhA!MGMd4w9ii67jutDBh_s5w1ZdT7uYpVPhJtGEe1JqfNk

Is this possibile or i still have to defining that big file? If it is how can i make it?

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted

EDIT: I've looked at the Strucutre Block class and i found out how to load a structure. But for some reason if i generate a new world and (for example) try to load this structure right-clicking an item it seems like the game can't find the structure (wich is stored in the structures folder into resources). This is the dummy item class i use to "spawn" the structure

public class ItemMW extends Item {

public ItemMW(CreativeTabs tab) {
	this.setCreativeTab(tab);
}

@Override
public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn,
		EnumHand hand) {
	if (!worldIn.isRemote)
		this.func_189714_c(playerIn.getPosition(), worldIn);
	return super.onItemRightClick(itemStackIn, worldIn, playerIn, hand);
}

public boolean func_189714_c(BlockPos pos, World world) {
	WorldServer worldserver = (WorldServer) world;
	MinecraftServer minecraftserver = world.getMinecraftServer();
	TemplateManager templatemanager = worldserver.getStructureTemplateManager();
	Template template = templatemanager.func_189942_b(minecraftserver, new ResourceLocation(MW.MODID + ":" + "structures/pagoda.nbt"));

	if(template == null)
	{
		System.out.println("NO STRUCTURE");
		return false;
	}
	BlockPos blockpos2 = template.getSize();
	IBlockState iblockstate = world.getBlockState(pos);
	world.notifyBlockUpdate(pos, iblockstate, iblockstate, 3);
	PlacementSettings placementsettings = (new PlacementSettings()).setMirror(Mirror.NONE)
			.setRotation(Rotation.NONE).setIgnoreEntities(false).setChunk((ChunkPos) null)
			.setReplacedBlock((Block) null).setIgnoreStructureBlock(false);

	template.addBlocksToWorldChunk(world, pos.add(0, 1, 0), placementsettings);
	return true;
}

}

 

The NBT file is stored into resources-assets-mw-structures-pagoda.nbt (mw is the mod id)

EDIT 2: Found out a way to make it works. The problem was (as i suspected) in the ResourceLocation, that for some reason pointed at a wrong location. By changing that i can spawn my structure and also integrating this function into (for example) a biome class i can spawn it randomly in the world using the nbt file :D

public void loadStructure(BlockPos pos, World world, String name) {
	WorldServer worldserver = (WorldServer) world;
	MinecraftServer minecraftserver = world.getMinecraftServer();
	TemplateManager templatemanager = worldserver.getStructureTemplateManager();
	ResourceLocation loc = new ResourceLocation(MW.MODID, name);
	Template template = templatemanager.func_189942_b(minecraftserver, loc);

	if (template != null) {
		IBlockState iblockstate = world.getBlockState(pos);
		world.notifyBlockUpdate(pos, iblockstate, iblockstate, 3);
		PlacementSettings placementsettings = (new PlacementSettings()).setMirror(Mirror.NONE)
				.setRotation(Rotation.NONE).setIgnoreEntities(false).setChunk((ChunkPos) null)
				.setReplacedBlock((Block) null).setIgnoreStructureBlock(false);

		template.addBlocksToWorldChunk(world, pos.add(0, 1, 0), placementsettings);
	}
}

  • Like 2

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted

This seems awesome. I'm trying to figure out how to use it, though... I'm not really sure how to check for a block, then determine if it's a block above ground? Like, I want the structure to spawn on the ground instead of underground, or in the air, or anything like that. Granted, I can't get it to spawn in any of those places either... This is my surface (overworld) generator code:

 


    //The actual generation method.
    private void generateSurface(World world, Random rand, int chunkX, int chunkZ) {
        for (int k = 0; k < 16; k++)
        {
            int firstBlockXCoord = chunkX + rand.nextInt(16);
            int firstBlockZCoord = chunkZ + rand.nextInt(16);
            //Will be found between y = 0 and y = 20
            int worldY = rand.nextInt(20);
            BlockPos worldPos = new BlockPos(firstBlockXCoord, worldY, firstBlockZCoord);
                //The 10 as the second parameter sets the maximum vein size
            IBlockState state = world.getBlockState(worldPos);
		if (state.getBlock().canPlaceBlockAt(world, worldPos)){
			SureenStructureGen structureGen = new SureenStructureGen();
			structureGen.loadStructure(worldPos, world, "Pony Home");
		}
        }
    }

Posted

How do you export an NBT file? What program do you use? Or how do you do it??

Disclaimer:  I been told to keep my opinions to myself, to shut up and that I am spreading lies and misinformation or even that my methods are unorthodox and or too irregular. Here are my suggestions take it or leave it.

Posted

@SureenInk

I simply pass this block pos as position to spawn the structure

worldIn.getTopSolidOrLiquidBlock(pos)

 

Consider that i use this in the decoration function of my biome, but i guess that you can use it in the world generator too

 

@trollworkout

The nbt file is generated using Structure Block in the game it-self. Note that the structure can't be larger than 32x32x32. Once i saved the strucutre i then put into a folder (in my mod assets) called "structures", so i can load it in every world i want

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted

Ahh, yeah... I never was taught about decoration stuff at all. I was only shown how to use the world generator. I lack the ability to learn without being taught, so I've never done it any other way ^^" I'll give using that line a try, though, thanks.

Posted

Ahahahaah just remember that the getTopOrSolidBlock works for the first block of the structure (so you can have a structure that is one block on ground and the rest in the air). I'm trying to find how to get the structure dimension to check if there's enough space to generate, i'll update as soon as i find it ;)

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted

Ok, just figured out how to get the exact size of the strucutre (and it was easier than i thought). Just use template.getSize(). Note that despite the fact it return a block pos this will have the size of the structure. So, if you do template.getSize().getX() you'll have how "long" the structure is (how many blocks on the X axis the structure have). If you do template.getSize().getZ() you'll get how "deep" the structure is (how many blocks on the Z axis the structure have). If you do template.getSize().getY() you'll get how "tall" the structure is (how many blocks on the Y axis the structure have). Knowing this is then easy to check if a structure can spawn. For example i use this for loop that (in case the structure can spawn) will place it at the center of the choosen area

for (int i = -1 * template.getSize().getX()/2; i < template.getSize().getX()/2 + 1; i++) {
				for (int j = -1 * template.getSize().getZ(); j < template.getSize().getZ()/2 + 1; j++) {
					if (!world.getBlockState(pos.add(i, 0, j)).getBlock().equals(Blocks.GRASS)
							&& !world.getBlockState(pos.add(i, 0, j)).getBlock().equals(Blocks.DIRT)) {
						flag = false;
						break;
					}
				}
			}

 

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted

Do you know if there's a way to make multiple structures spawn next to each other? Like, if my structure requires 4 structure blocks to spawn it. Is there a way I could tell it like... "spawn this first part, then go over x squares and spawn part 2"?

Posted

I guess you can just call the same code but with different position. For instance, let's say you have 2 parts of the structure, and the second is 20 block away on the X axis from the first part. I think you can generate the first part passing a position as a parameter and then re-call that function but passing position.add(20, 0, 0) and of course the name of the other structure part

Don't blame me if i always ask for your help. I just want to learn to be better :)

  • 5 months later...
Posted (edited)

Okay, I'm very confused. Please, explain this to me like I'm five. 

Basically, what I need is a mod that creates a central folder. Into this folder, I can put pre-created nbt structures, which will then randomly generate upon creating a new world. Is that what this is? If so, where can I download it?

Edited by WalterTheMighty
contained slur
Posted

As diesieben said this was for an help on generating structures using nbt files created by structure blocks. By the way i heard once there was a mod that put nbt structures into the overworld as natural structures, but i don't remember its name unfortunately

Don't blame me if i always ask for your help. I just want to learn to be better :)

  • 1 month later...
Posted (edited)

Forgive me for opening up an old topic, but does this work anymore?

I have recently been designing a mod (for 1.10.2) that requires structures, and came across this (very good) solution I used basically the exact same code as Jimil (except i replaced the func_ with getTemplate) and I know my structure is working as I can load it from a structure block, I have it print out the contents of template and player location and resource location, it doesn't give me any errors, it just doesn't load. can anyone here help me?

Edited by Acrogenous
  • 2 weeks later...
Posted (edited)
On 5/13/2017 at 4:34 PM, Acrogenous said:

Forgive me for opening up an old topic, but does this work anymore?

I have recently been designing a mod (for 1.10.2) that requires structures, and came across this (very good) solution I used basically the exact same code as Jimil (except i replaced the func_ with getTemplate) and I know my structure is working as I can load it from a structure block, I have it print out the contents of template and player location and resource location, it doesn't give me any errors, it just doesn't load. can anyone here help me?

I have the same problem now, and nothing is generated in the world (on test item right click), no metter do I use get or getTemplate functions, maybe someone can help? I tried everything... Here is my code:

 

	if (!worldIn.isRemote) {
		WorldServer worldserver = (WorldServer) worldIn;
		MinecraftServer minecraftserver = worldIn.getMinecraftServer();
		TemplateManager templatemanager = worldserver.getStructureTemplateManager();
		 
		Template template = templatemanager.get(minecraftserver, new ResourceLocation(Reference.MOD_ID,"structures/test2.nbt"));
		Utils.getLogger().info("=======1======="+template);
		if (template != null) {   
			worldIn.notifyBlockUpdate(pos, iblockstate, iblockstate, 3);
			PlacementSettings placementsettings = (new PlacementSettings()).setMirror(Mirror.NONE)
					.setRotation(Rotation.NONE).setIgnoreEntities(false).setChunk((ChunkPos) null)
					.setReplacedBlock((Block) null).setIgnoreStructureBlock(false);

			template.addBlocksToWorld(worldIn, pos.add(0, 1, 0), placementsettings);
			Utils.getLogger().info("========2======="+template);
		}
	}

 

Console gives me this result for loggers:

=======1=======net.minecraft.world.gen.structure.template.Template@1bca1033
========2=======net.minecraft.world.gen.structure.template.Template@1bca1033

Edited by myWitch
  • 2 weeks later...
Posted

The reason could be that you are searching for this resource
 

new ResourceLocation(Reference.MOD_ID,"structures/test2.nbt")


This will actually search for the file in structures/structures/test2.nbt, wich i believe doesn't exist. So you should just type the name of the structure in your structures folder (if is not in a sub folder). Searching for this resource instead will mostly solve your issue. That was my bad that i didn't specified earlier and i'm sorry for this. Let me know if it works after this change ;)
 

new ResourceLocation(Reference.MOD_ID,"test2.nbt")

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted
1 hour ago, JimiIT92 said:

The reason could be that you are searching for this resource
 


new ResourceLocation(Reference.MOD_ID,"structures/test2.nbt")


This will actually search for the file in structures/structures/test2.nbt, wich i believe doesn't exist. So you should just type the name of the structure in your structures folder (if is not in a sub folder). Searching for this resource instead will mostly solve your issue. That was my bad that i didn't specified earlier and i'm sorry for this. Let me know if it works after this change ;)
 


new ResourceLocation(Reference.MOD_ID,"test2.nbt")

JimilT92, thank you very much for your answer. I tried this too with no success ((( actually I tried tones of variants, including rewriting of addBlocksToWorld function... Here is the last variant that gives not null template, but nothing spawns, so I'm really stuck on it :((( I put this code right into onItemRightClick, but I think it doesn't matter if I put it somewhere as a separate function... Test file t1.nbt is in structures folder and I checked it by using structure block loading - it's good. You can also see some variants that I've tried in commented lines... If you can give me any ideas I would be realy happy )) It's the last thing to be solved for my mod.

 

if (!worldIn.isRemote) {
					WorldServer worldserver = (WorldServer) worldIn;
					MinecraftServer minecraftserver = worldIn.getMinecraftServer();
					TemplateManager templatemanager = worldserver.getStructureTemplateManager();
					ResourceLocation loc = new ResourceLocation(Reference.MOD_ID,"structures/t1.nbt");
					Template template = templatemanager.getTemplate(minecraftserver, loc); //.get(minecraftserver, new ResourceLocation(Reference.MOD_ID,"t1.nbt"));
					Utils.getLogger().info("=======0======="+template);
					if (template != null) {   
						worldIn.notifyBlockUpdate(pos, iblockstate, iblockstate, 3);
						PlacementSettings placementsettings = (new PlacementSettings()).setMirror(Mirror.NONE)
								.setRotation(Rotation.NONE).setIgnoreEntities(false).setChunk((ChunkPos) null)
								.setReplacedBlock((Block) null).setIgnoreStructureBlock(false);
						
						Utils.getLogger().info("=======1======="+loc);
						
						//template.addBlocksToWorld(worldIn, pos, new BlockRotationProcessor(pos, placementsettings), placementsettings, 1);
						
						//template.addBlocksToWorld(worldIn, pos.add(0, 1, 0), placementsettings);
						template.addBlocksToWorldChunk(worldIn, pos, placementsettings); 
						
						Utils.getLogger().info("========2======="+template);
					}
				}

 

Posted
ResourceLocation loc = new ResourceLocation(Reference.MOD_ID,"structures/t1.nbt");

- if I change this code to the one below - it's also not working, I tried indeed ((

ResourceLocation loc = new ResourceLocation(Reference.MOD_ID,"t1.nbt");
Posted

Mmmm, then i have no clue why this is not working for you :/ I'll post here an example of working class i'm using that spawns an obelisk in the world

	public class WorldGenObelisk {
	    private int mirror;
    private int rotation;
	    public WorldGenObelisk(BlockPos pos, World world) {
        mirror = MW.rand.nextInt(Mirror.values().length);
        rotation = MW.rand.nextInt(Rotation.values().length);
        
        this.loadStructure(pos, world, "obelisk", true);
	    }
	    public void loadStructure(BlockPos pos, World world, String name, boolean check) {
        boolean flag = false;
        if (!world.isRemote) {
            WorldServer worldserver = (WorldServer) world;
            MinecraftServer minecraftserver = world.getMinecraftServer();
            TemplateManager templatemanager = worldserver.getStructureTemplateManager();
            ResourceLocation loc = new ResourceLocation(MW.MODID, name);
            Template template = templatemanager.func_189942_b(minecraftserver, loc);
	            if (template != null) {
                IBlockState iblockstate = world.getBlockState(pos);
                world.notifyBlockUpdate(pos, iblockstate, iblockstate, 3);
	                flag = true;
                if (check) {
                    
                    for (int i = 0; i < template.getSize().getX(); i++) {
                        for (int j = 0; j < template.getSize().getZ(); j++) {
                            BlockPos down = pos.add(i, -1, j);
                            Block b = world.getBlockState(down).getBlock();
                            if (!b.equals(Blocks.SAND)) {
                                flag = false;
                            }
                        }
                    }
                }
	                if (flag) {
	                    PlacementSettings placementsettings = (new PlacementSettings()).setMirror(Mirror.values()[mirror])
                            .setRotation(Rotation.values()[rotation]).setIgnoreEntities(false).setChunk((ChunkPos) null)
                            .setReplacedBlock((Block) null).setIgnoreStructureBlock(true);
                    
                    template.addBlocksToWorldChunk(world, pos.down(), placementsettings);
                }
	            }
        }
    }
}


This class is called from the WorldGenMinable class, in the generateOverworld method (so where you put the code to spawn ores) by doing this

if (world.getBiomeGenForCoords(new BlockPos(x, 60, z)).equals(Biomes.DESERT) && random.nextInt(70) == 1) {
            int randPosX = x + random.nextInt(35);
            int randPosZ = z + random.nextInt(35);
            int randPosY = 60 + random.nextInt(255 - 64);
            BlockPos position = new BlockPos(randPosX, randPosY, randPosZ);
            if (!(world.getBlockState(world.getTopSolidOrLiquidBlock(position)).getBlock().equals(Blocks.WATER)))
                new WorldGenObelisk(world.getTopSolidOrLiquidBlock(position), world);
        }



Notice that in the structure class it will also check if the spawn area is a valid area, you can remove that if you want. I hope this help, if not you can try looking at how Structure Blocks load structures and edit that code (since is exactly what i've done, maybe some small changes has been made but since is still 1.10.2 i don't think so)

  • Like 2

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted
21 hours ago, myWitch said:

if I change this code to the one below - it's also not working,

What did you see happening when you set breakpoints and used the debugger to step through the code that's trying to generate your structure?

  • Like 1

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 (edited)

Thank you very much for your attention, finally it's working! I'll tell you what was wrong, maybe someone will need it. I started with deep debug of  these lines:
ResourceLocation loc = new ResourceLocation(Reference.MOD_ID,"t1.nbt");

Template template = templatemanager.getTemplate(minecraftserver, loc); 

And I've found that now minecraft simply adds ".nbt", no need to put it here in a file name! So, file extension was doubles and I've got no structure as a result.

Edited by myWitch
Posted

 Here I'll show the final code that definitly works for me:

 //spawn structure  
				if (!worldIn.isRemote) {
					WorldServer worldserver = (WorldServer) worldIn;
					MinecraftServer minecraftserver = worldIn.getMinecraftServer();
					TemplateManager templatemanager = worldserver.getStructureTemplateManager();
					ResourceLocation loc = new ResourceLocation(Reference.MOD_ID,"t1");
					Template template = templatemanager.getTemplate(minecraftserver, loc); 
					Utils.getLogger().info("=======0======="+template);
					if (template != null) {   
						worldIn.notifyBlockUpdate(pos, iblockstate, iblockstate, 3);
						PlacementSettings placementsettings = (new PlacementSettings()).setMirror(Mirror.NONE)
								.setRotation(Rotation.NONE).setIgnoreEntities(false).setChunk((ChunkPos) null)
								.setReplacedBlock((Block) null).setIgnoreStructureBlock(false);
						
						Utils.getLogger().info("=======1======="+loc);
						
						 
						template.addBlocksToWorld(worldIn, pos, placementsettings);
						 
						Utils.getLogger().info("========2======="+pos);
					}
				}

 

  • Like 3
Posted
Just now, myWitch said:

 Here I'll show the final code that definitly works for me:


 //spawn structure  
				if (!worldIn.isRemote) {
					WorldServer worldserver = (WorldServer) worldIn;
					MinecraftServer minecraftserver = worldIn.getMinecraftServer();
					TemplateManager templatemanager = worldserver.getStructureTemplateManager();
					ResourceLocation loc = new ResourceLocation(Reference.MOD_ID,"t1");
					Template template = templatemanager.getTemplate(minecraftserver, loc); 
					Utils.getLogger().info("=======0======="+template);
					if (template != null) {   
						worldIn.notifyBlockUpdate(pos, iblockstate, iblockstate, 3);
						PlacementSettings placementsettings = (new PlacementSettings()).setMirror(Mirror.NONE)
								.setRotation(Rotation.NONE).setIgnoreEntities(false).setChunk((ChunkPos) null)
								.setReplacedBlock((Block) null).setIgnoreStructureBlock(false);
						
						Utils.getLogger().info("=======1======="+loc);
						
						 
						template.addBlocksToWorld(worldIn, pos, placementsettings);
						 
						Utils.getLogger().info("========2======="+pos);
					}
				}

 

I used to follow an old tutorial in 1.8.9 but if you use nbt files to spawn structures do you still use IWorldGenerators or you just simply make a class that grabs the location of your nbt structure and generate them? Sorry for being old the future is now old man!

Posted

@TheRPGAdventurer the benefit of this is that you can use whatever you want. You can use a class that implements an IWorldGenerator and in the generate method call this code, or you can create a simple class without IWorldGenerator and call it where you want (from example from the biome generator or the WorldGenMinable class). You can even spawn the structure at a specific location (for example you want a structure that is unique per world and is always generated at 0,0. With this type of generation you can do it pretty easy), you can randomize the inside using the Data structure blocks and check for them during the generation of the structure, and more. BUt to answer your question: no, you don't necessairly need an IWorldGenerator. As i said you can use it of course, for instance to avoid some errors if you want to port your structures to this system

Don't blame me if i always ask for your help. I just want to learn to be better :)

Posted
On 6/10/2017 at 5:13 AM, TheRPGAdventurer said:

if you use nbt files to spawn structures do you still use IWorldGenerators or...

 

Explore this call in Witch's code:

On 6/10/2017 at 5:13 AM, TheRPGAdventurer said:

template.addBlocksToWorld(worldIn, pos, placementsettings);

 

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.

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

    • It is 1.12.2 - I have no idea if there is a 1.12 pack
    • Okay, but does the modpack works with 1.12 or just with 1.12.2, because I need the Forge client specifically for Minecraft 1.12, not 1.12.2
    • 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() ); } }  
  • Topics

×
×
  • Create New...

Important Information

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