Jump to content

Recommended Posts

Posted

I'm making a little mod with food, armors and tools and I need to generate my crops inside my world. (Like Wild Crops)

One should spawn only near water like sugar canes one randomly on a farmland block. I have already my seeds and crops but my WorldGen class for my crops is empty because I don't know where to start (Never did it).

Can someone help me? Maybe without a full code but guiding me throw the generating.

Thanks

Posted

This is how I usually create my worldgen features

  1. Implement IWorldGenerator in your worldgen class(es). This will give you access to a generate method which will be called during worldgen.
  2. Be sure to check what Dimension(id) and/or what WorldType is being used by the current world. Don't think you want to generate stuff in the Nether/End etc.
  3. The mentioned generate method will give you a chunkX & chunkZ parameters. Do not multiply by 16 to get blockcoords, but rather use bit-shifting (blockpos = chunkpos << 4).
    1. Whilst multiplication from chunkpos to blockpos will result in correct numbers, division (block->chunk) will result in incorrect values for negative coordinates, due to how integers are rounded. It is for the best to consistently use one method to calculate rather than mix-and-match based on the situation.
  4. Always try to generate your features inside of the currently generating chunk. Do not generate along the border. This can cause cascading chunk-generations, and cause lag.
    Add 8 to both your x & z block-coordinates to get the (almost) centre of the current chunk, then use a random value between -7 to 7 (min-max values) to truly get a random position within the chunk. As for y-coordinates, you can use World::getTopSolidOrLiquidBlock to get the top-most solid y-value. Be sure to check if it is not a fluid though!
  5. For your normal crops, you only need to check for Dirt or Grass blocks, switch them out for Farmland (be sure to place some water next to it) and then place the crop ontop of that
  6. Sugarcane is a bit trickier. You can have a look through the WorldGenReed class in your IDE to see how Vanilla spawns Sugarcane
  7. Lastly, you need to register your IWorldGenerator implementing class during  init (FMLInitializationEvent) using GameRegistry.registerWorldGenerator(WorldGenerator, weight) where weight is an integer determining when they are run. Higher weights tend to run after generators with less weight.

Also previously known as eAndPi.

"Pi, is there a station coming up where we can board your train of thought?" -Kronnn

Published Mods: Underworld

Handy links: Vic_'s Forge events Own WIP Tutorials.

Posted

This is for an older version, but I think the basic idea still works as an example:

GenerateHerbs.java

 

Note that I did not think to explicitly check dimensions, though the herbs would not have been prevented by other functions.  Note the isLocationValid method at the end: This actually asks each herb if it should generate, and I think that is a good pattern -- vanilla basically does the same thing with mob spawns.  So each of your crops would have some kind of "canGenHere" method(s) and you would then put tests for that specific crop there.

Developer of Doomlike Dungeons.

Posted (edited)
3 hours ago, Matryoshika said:

This is how I usually create my worldgen features

  1. Implement IWorldGenerator in your worldgen class(es). This will give you access to a generate method which will be called during worldgen.
  2. Be sure to check what Dimension(id) and/or what WorldType is being used by the current world. Don't think you want to generate stuff in the Nether/End etc.
  3. The mentioned generate method will give you a chunkX & chunkZ parameters. Do not multiply by 16 to get blockcoords, but rather use bit-shifting (blockpos = chunkpos << 4).
    1. Whilst multiplication from chunkpos to blockpos will result in correct numbers, division (block->chunk) will result in incorrect values for negative coordinates, due to how integers are rounded. It is for the best to consistently use one method to calculate rather than mix-and-match based on the situation.
  4. Always try to generate your features inside of the currently generating chunk. Do not generate along the border. This can cause cascading chunk-generations, and cause lag.
    Add 8 to both your x & z block-coordinates to get the (almost) centre of the current chunk, then use a random value between -7 to 7 (min-max values) to truly get a random position within the chunk. As for y-coordinates, you can use World::getTopSolidOrLiquidBlock to get the top-most solid y-value. Be sure to check if it is not a fluid though!
  5. For your normal crops, you only need to check for Dirt or Grass blocks, switch them out for Farmland (be sure to place some water next to it) and then place the crop ontop of that
  6. Sugarcane is a bit trickier. You can have a look through the WorldGenReed class in your IDE to see how Vanilla spawns Sugarcane
  7. Lastly, you need to register your IWorldGenerator implementing class during  init (FMLInitializationEvent) using GameRegistry.registerWorldGenerator(WorldGenerator, weight) where weight is an integer determining when they are run. Higher weights tend to run after generators with less weight.

I reply a bit late but I was trying. I know, I didn't add everything you said but I'm learning this world gen

@Override
	public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator,
			IChunkProvider chunkProvider) {
		if (world.provider.getDimension() == 0) {
			for (int i = 0; i < 64; i++) {

				int X = random.nextInt(16);
				int Z = random.nextInt(16);
				int Y = 0;
				System.out.println("1");
				BlockPos surface = world.getTopSolidOrLiquidBlock(new BlockPos(X,Y, Z));
				BlockPos blockpos1 = surface.down();
				System.out.println("2");
				System.out.println("Y: " + surface);
					if (world.isAirBlock(surface) && world.provider.isSurfaceWorld() && world.getBlockState(blockpos1).getBlock() == Blocks.GRASS
							|| world.getBlockState(blockpos1).getBlock() == Blocks.DIRT) {
						System.out.println("3");
						if (InitBlocks.RICE_CROP.canPlaceBlockAt(world, surface)) {
							System.out.println("4");
							world.setBlockState(blockpos1, Blocks.FARMLAND.getDefaultState(), 2);
							System.out.println("Attemping to place a farmland at X: " + X + ", Y: " + Y + ", Z: " + Z);
							world.setBlockState(surface, InitBlocks.RICE_CROP.getDefaultState());
							System.out.println("Attemping to place a rice crop at X: " + X + ", Y: " + Y + ", Z: " + Z);
					}
				}
			}
		}
	}

This is my class now, I have spam of 1, 2 and "surface". Help me to solve. I don't want a solution or I won't learn it and next world gen I will get the same error

This is my "surface" spam:

Cattura.thumb.PNG.be18c7619785aa56794608b8b66a8158.PNG

 

Edit: Now "Work" but sometimes try to spawn at Y = 0

and spawn like 64 farmlands but I know why

 

Edit 2: It attempts to spawn farmland and crop in water

Edited by Cris16228
Posted (edited)

Your if-statement is faulty.
 

43 minutes ago, Cris16228 said:

BlockPos surface = world.getTopSolidOrLiquidBlock(new BlockPos(X,Y, Z));

 

43 minutes ago, Cris16228 said:

world.isAirBlock(surface)

surface here will always be a non-air-block. You have to check if surface.up() is an air-block, not the one that is guaranteed not to be.

Further-more, if you simplify your entire if-statement to if(A && B && C || D) then the logic is easier to see. if A, B and C are true, OR if D is true, then continue. Dirt-blocks will always pass this check, even if the air-block or surfaceWorld are false. You need to wrap C and D inside a parenthesis. if(A && B && (C || D)), to continue if either of those two are true, whilst still relying on the A and B checks.

 

43 minutes ago, Cris16228 said:

Edit 2: It attempts to spawn farmland and crop in water

3 hours ago, Matryoshika said:

As for y-coordinates, you can use World::getTopSolidOrLiquidBlock to get the top-most solid y-value. Be sure to check if it is not a fluid though!

Edited by Matryoshika

Also previously known as eAndPi.

"Pi, is there a station coming up where we can board your train of thought?" -Kronnn

Published Mods: Underworld

Handy links: Vic_'s Forge events Own WIP Tutorials.

Posted
11 minutes ago, Matryoshika said:

Your if-statement is faulty.
 

 

surface here will always be a non-air-block. You have to check if surface.up() is an air-block, not the one that is guaranteed not to be.

Further-more, if you simplify your entire if-statement to if(A && B && C || D) then the logic is easier to see. if A, B and C are true, OR if D is true, then continue. Dirt-blocks will always pass this check, even if the air-block or surfaceWorld are false. You need to wrap C and D inside a parenthesis. if(A && B && (C || D)), to continue if either of those two are true, whilst still relying on the A and B checks.

@Override
	public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator,
			IChunkProvider chunkProvider) {
		int spawnInChunks = random.nextInt(7) + 1;
		if (world.provider.getDimension() == 0) {
			for (int i = 0; i < spawnInChunks; i++) {
				
				int X = random.nextInt(16);
				int Z = random.nextInt(16);
				int Y = 0;
				BlockPos surface = world.getTopSolidOrLiquidBlock(new BlockPos(X, Y, Z));
				BlockPos blockpos1 = surface.down();
				if (world.isAirBlock(surface.up()) && world.provider.isSurfaceWorld()
						&& (world.getBlockState(blockpos1).getBlock() == Blocks.GRASS
								|| world.getBlockState(blockpos1).getBlock() == Blocks.DIRT)) {
					if (InitBlocks.RICE_CROP.canPlaceBlockAt(world, surface)) {
						world.setBlockState(blockpos1.north(), Blocks.WATER.getDefaultState(), 2);
						world.setBlockState(blockpos1, Blocks.FARMLAND.getDefaultState(), 2);
						world.setBlockState(surface,
								InitBlocks.RICE_CROP.getDefaultState().withProperty(RiceCrop.AGE, 7));
					}
				}
			}
		}
	}

Never found a crop in 5 mins, is there a way to generate them a bit more near the player and not 200+ blocks away? (I'm using IDE Minecraft with 10 render distance)

Posted
23 minutes ago, Cris16228 said:

int spawnInChunks = random.nextInt(7) + 1;

You could make this higher

About Me

Spoiler

My Discord - Cadiboo#8887

My WebsiteCadiboo.github.io

My ModsCadiboo.github.io/projects

My TutorialsCadiboo.github.io/tutorials

Versions below 1.14.4 are no longer supported on this forum. Use the latest version to receive support.

When asking support remember to include all relevant log files (logs are found in .minecraft/logs/), code if applicable and screenshots if possible.

Only download mods from trusted sites like CurseForge (minecraft.curseforge.com). A list of bad sites can be found here, with more information available at stopmodreposts.org

Edit your own signature at www.minecraftforge.net/forum/settings/signature/ (Make sure to check its compatibility with the Dark Theme)

Posted
1 minute ago, Cadiboo said:

You could make this higher

The problems are:
1) They are all together and I wanted, if possible, put them randomly in a chunk

2) The code up not work, never generate my crops or causes cascading worldgen lag

3) They spawn far from me (I always generate a new world). I don't want them within 2 blocks when creating a world just asking if it's normal

Posted

Any help? The code seems to work but if there are some fixes for my code or any suggestion on how to change the spawn per chunk, spread them more in the chunk and generate my crops also near me and not far

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.