Jump to content

Recommended Posts

Posted

Okay, basically Forge provides an event called InitMapGenEvent which is meant for exactly this sort of thing -- changing the way vanilla map gen happens. So you need to make an event handling method to handle that event.

 

Then in that event you need to check if it is being fired for caves, so you can check if (event.getType() == EventMapGenEvent.EventType.CAVE) and if that is true then use the event.setNeGen() to your custom cave generator.

 

For the custom cave generator, make a new class and copy all the code from the MapGenCaves class. Then depending on what you want to do, look at the code and figure out how to add your crystal blocks.

 

That's pretty much it. Try the two steps -- handle the event and make your custom class -- and if you have trouble then post your code and we can help further.

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

Posted (edited)

But how do i tell my crystals to call that event and where? in the crystal class or generate class? (sry for this question, im new at coding) ;P

Edited by StudioMaker
Posted

Its ok, i fixed it. But i have some problems, first is that they dont spawn on the groundin the caves, they spawn in the air in caves. And second is that they can only connect to the ground, and it looks weird. With that i mean that for example if i place it on the side of a block it will only point down

Posted (edited)

How I would do it is check to make sure that only on of the blocks connecting to the crystal is stone and the rest air. The orientate the block depending on which block is stone. If you want it to be able to be placed when there are other blocks to its side then choose an order to check where there are blocks connected to it and have its orientation set depending on which is the first block in the order to be there.

Edited by Euan
Posted (edited)

Unfortunately I'm not at my pc at the moment but if my memory serves me correctly then you get a position with the block. Things inside the cave I believe are decided at the very end of the generation of the cave so you'll be able to check the blocks around the block being spawned using a sub method of World (or maybe in the generator?). From that you can spawn it according to the conditions. As for the setting a priority to which orientation it would simply require an else if block. Then in the order you want check to make sure that the side you want orientated is stone and the majority of the other sides have air next to it.

Edited by Euan
Posted

It's not really right to keep asking for examples. This is your code and your mod and it is very rare that someone has done exactly what you want to do (and if they have then what is the point of you making the mod?). Everyone here learned by trying and so you need to to. Post the code that you have so far, explain the things you've tried (like looking at other blocks that do something similar when placed) and explain the steps you took to debug -- did you use debugger in Eclipse to track the block state, or did you print it out to the console?

 

Those are the steps a person should do. Please post code and explanation of what you've discovered in your debugging.

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

Posted

Well yeah im very new to modding (Not that new to coding tho but quite new to java coding) and yeah i know that i wont learn by copying a code, but i gotta start somewhere i cant start with empty hands. Its quite hard to just "test" things out on js because its soo much stuff that needs to be right, and its hard to experiment. But i have tried and i just got stuck here. Im learning best if i know the code, and then i can figure out whats going on in it. Thats how i learned all the start things you need to know, because think it like this, its easier to earn money if u already got money. And yeah all the code i got is just a mess rn, but i managed to fix some bugs, create that they do only spawn in caves, but idk the rest. 

Posted

And what i ment with example was that i just wanted a more simple version , because im not a modding expert like u guys and yeah its hard if someone just tells me what i need to do, because yeah im trying to learn and if i already knew how and what to do i wouldn't have asked this before

Posted

I understand it takes a bit of time to get going. By the way did you know I have a bunch of tutorials to get people started? Check them out at http://jabelarminecraft.blogspot.com/.

 

The problem is you have started with something (world gen) which is one of the tougher topics honestly, mostly because the vanilla code is pretty convoluted.

 

For your particular problem though of the crystal only pointing down, the first thing to is look at how similar blocks behave. Like a torch or a fence that "senses" how it is placed to figure out how the model should look.

 

Also, you really need to post code to get any significant help. Don't be too embarrassed (although Draco18s might make fun of you!) if your code is wrong. It is important for us to understand where you're really at and what kinda help you need.

 

So at least tell me you've tried to research torches or similar and let us know what you've found about how they work.

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

Posted

k sure, idk i have just tried to fix diffrent things soo yes in this code there will be weird stuff but k, I have tried for so long to be able to make the crystal to be able to face all directions, i have tried adding some code from vanilla mc blocks that can face all directions on blocks for example button, followed every single thing on the internet, and it crashes or just dont work when i have tried. This is the crystal class rn and yeah there is things that i have just left etc but well well 

package com.studiomaker.poweredelements2.blocks;

import java.util.Random;

import javax.annotation.Nullable;

import com.studiomaker.poweredelements2.init.ModItems;
import com.studiomaker.poweredelements2.init.InitMapGenEvent.EventType;

import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.Item;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.gen.MapGenBase;


public class Crystal extends BlockBase 
{
		
	public Crystal(String name, Material material) 
	{
		super(name, material);
		setSoundType(SoundType.GLASS);
		setHardness(1.0F);
		setResistance(10F);
		setHarvestLevel("pickaxe", 3);
	}
	public Item getItemDropped(IBlockState state, Random rand, int fortune)
    {
        return ModItems.CROSSED_CRYSTAL;
    }
	public int quantityDropped(Random random)
    {
        return 2 + random.nextInt(6);
    }


	    @Nullable
	    public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos)
	    {
	        return NULL_AABB;
	    }


	@Override
    public BlockRenderLayer getBlockLayer() {
        return BlockRenderLayer.TRANSLUCENT;
    }
	@Override
    public boolean isOpaqueCube(IBlockState state) 
    {
        return false;
    }

    @Override
    public boolean isFullCube(IBlockState state) 
    {
        return false;
    }
    
    @Override
    public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
    {
        return super.onBlockPlaced(worldIn, pos, facing, hitX, hitY, hitZ, meta, placer).withProperty(FACING, facing);
    }
    
    
    public static enum EventType {CAVE}

    
    
}

 

And here is the gen class 

package com.studiomaker.poweredelements2.world.gen;

import java.util.Random;

import com.studiomaker.poweredelements2.init.ModBlocks;
import com.studiomaker.poweredelements2.util.handlers.EnumHandler;

import net.minecraft.block.state.pattern.BlockMatcher;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.IChunkGenerator;
import net.minecraft.world.gen.feature.WorldGenMinable;
import net.minecraft.world.gen.feature.WorldGenerator;
import net.minecraftforge.fml.common.IWorldGenerator;
import net.minecraftforge.fml.common.Mod.EventHandler;

public class WorldGenCustomOres implements IWorldGenerator
{
	private WorldGenerator crystal;
	private WorldGenerator fade_ore_block;
	private WorldGenerator energetic_ore_block;
	
	public WorldGenCustomOres() 
	{
		crystal= new WorldGenMinable(ModBlocks.CRYSTAL.getDefaultState(), 3, BlockMatcher.forBlock(Blocks.AIR));
		
		fade_ore_block = new WorldGenMinable(ModBlocks.FADE_ORE_BLOCK.getDefaultState(), 5, BlockMatcher.forBlock(Blocks.STONE));
		
		energetic_ore_block = new WorldGenMinable(ModBlocks.ENERGETIC_ORE_BLOCK.getDefaultState(), 5, BlockMatcher.forBlock(Blocks.STONE));
	}
	
	@Override
	public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) 
	{
		switch(world.provider.getDimension())
		{
		case 0:
			
			runGenerator(crystal, world, random, chunkX, chunkZ, 50, 0, 35);
			runGenerator(fade_ore_block, world, random, chunkX, chunkZ, 50, 0, 100);
			runGenerator(energetic_ore_block, world, random, chunkX, chunkZ, 50, 0, 100);
			
		}
	}
	
	private void runGenerator(WorldGenerator gen, World world, Random rand, int chunkX, int chunkZ, int chance, int minHeight, int maxHeight)
	{
		if(minHeight > maxHeight || minHeight < 0 || maxHeight > 256) throw new IllegalArgumentException("Ore generated out of bounds");
		
		int heightDiff = maxHeight - minHeight + 1;
		for(int i = 0; i < chance; i++)
		{
			int x = chunkX * 16 + rand.nextInt(16);
			int y = minHeight + rand.nextInt(heightDiff);
			int z = chunkZ * 16 + rand.nextInt(16);
			
			gen.generate(world, rand, new BlockPos(x,y,z));
		}
	}
}

 

ps, dont make fun of it im new :P

Posted

Btw i fixed that they only spawn in caves by just letting them only spawn in air, and under 35 lel. And no i have still not figured out how to make them spawn on the ground and not free in the air

Posted (edited)

Okay, so by looking at BlockTorch I see that there is a property for which way it is facing. I think you should at least implement that -- there will be additional work to get it all working correctly, but the main point is your block has to have a location-based metadata (which is what a "property" represents) available to control the rendering and other behavior.

 

Edit: You'll also want to implement the getStateForPlacement() method.

Edited by jabelar

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

Posted

Well im pretty sure the problem is that i have to add enum facing thing, because it rn it should only face down (or its not facing down, but its facing the normal state) https://gyazo.com/9958fdf582b064966884d8a794f6b7b4, And for example if i place it on the side of a bloock its still facing down (normal state) https://gyazo.com/5ab57f4814932a60bd84d5ae7a00c202

And as i said im pretty sure i have to add some enum facing thing, and i have tried soooo much, and as i said it crashes or its not doing anyhting when i have tested.

Posted

Im pretty sure its something from this code (vanilla torch) that i need to add. But i have tried multiple times and it just crashes or wont work. 

public class BlockTorch extends Block
{
    public static final PropertyDirection FACING = PropertyDirection.create("facing", new Predicate<EnumFacing>()
    {
        public boolean apply(@Nullable EnumFacing p_apply_1_)
        {
            return p_apply_1_ != EnumFacing.DOWN;
        }
    });
    protected static final AxisAlignedBB STANDING_AABB = new AxisAlignedBB(0.4000000059604645D, 0.0D, 0.4000000059604645D, 0.6000000238418579D, 0.6000000238418579D, 0.6000000238418579D);
    protected static final AxisAlignedBB TORCH_NORTH_AABB = new AxisAlignedBB(0.3499999940395355D, 0.20000000298023224D, 0.699999988079071D, 0.6499999761581421D, 0.800000011920929D, 1.0D);
    protected static final AxisAlignedBB TORCH_SOUTH_AABB = new AxisAlignedBB(0.3499999940395355D, 0.20000000298023224D, 0.0D, 0.6499999761581421D, 0.800000011920929D, 0.30000001192092896D);
    protected static final AxisAlignedBB TORCH_WEST_AABB = new AxisAlignedBB(0.699999988079071D, 0.20000000298023224D, 0.3499999940395355D, 1.0D, 0.800000011920929D, 0.6499999761581421D);
    protected static final AxisAlignedBB TORCH_EAST_AABB = new AxisAlignedBB(0.0D, 0.20000000298023224D, 0.3499999940395355D, 0.30000001192092896D, 0.800000011920929D, 0.6499999761581421D);

    protected BlockTorch()
    {
        super(Material.CIRCUITS);
        this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.UP));
        this.setTickRandomly(true);
        this.setCreativeTab(CreativeTabs.DECORATIONS);
    }

    public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos)
    {
        switch ((EnumFacing)state.getValue(FACING))
        {
            case EAST:
                return TORCH_EAST_AABB;
            case WEST:
                return TORCH_WEST_AABB;
            case SOUTH:
                return TORCH_SOUTH_AABB;
            case NORTH:
                return TORCH_NORTH_AABB;
            default:
                return STANDING_AABB;
        }
    }

 

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

    • 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() ); } }  
    • Do you use features of inventory profiles next (ipnext) or is there a change without it?
  • Topics

×
×
  • Create New...

Important Information

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