Jump to content

Recommended Posts

Posted (edited)

I want to update a block (change it's state) after a certain period of time, if an action has been done. 

 

This is what I did just as a test, I know it's wrong. 

 

Spoiler

package mymod;

import java.util.Random;

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

public class Copper extends Block {
	
	private int i;

	public Copper(Properties properties) {
		
		super(properties);
	}
	
	@Override
	public void animateTick(BlockState stateIn, World worldIn, BlockPos pos, Random rand) {

		i++;

		if (i > 5) {

			worldIn.setBlockState(pos, Blocks.LAVA.getDefaultState());
		}
	}
}

 

 

This'll work for the first block and get it to turn into lava after 5 or however many ticks. I'm not sure what method to actually use, as the other tick ones are deprecated and don't work. I also need to be able to grab a capability in the method so that I can use that and not an instance variable that wont work when there are multiple instances. Or.....is there a better way altogether? 

Edited by MineModder2000
Posted (edited)

How exactly do I get boolean properties to work in blocks? I tried this :

 

Spoiler

 


public class Copper extends Block {
	
	public static final BooleanProperty LIT = BlockStateProperties.LIT;

	public Copper(Properties properties) {
		
		super(properties);
	}

	public boolean onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit) {
		
		worldIn.setBlockState(pos, state.with(LIT, Boolean.valueOf(true)), 1);  
	}
	
	@OnlyIn(Dist.CLIENT)
	public void animateTick(BlockState stateIn, World worldIn, BlockPos pos, Random rand) {
		
		if (stateIn.get(LIT)) {
				
        	// do stuff
                }
	}
}

 

But got this : Cannot set property BooleanProperty{name=lit, clazz=class java.lang.Boolean, values=[true, false]} as it does not exist in Block{mymod:copper}

Edited by MineModder2000
Posted (edited)
20 minutes ago, Animefan8888 said:

You need to override Block#fillBlockState

Ah, it's fillStateContainer actually. I am trying to make it do certain animations upon activation only, however nothing inside of my if statement within animateTick is run upon such. I set it to false on block added because its true by default. 

 

Spoiler

public class Copper extends Block {
	
	public static final BooleanProperty LIT = BlockStateProperties.LIT;

	public Copper(Properties properties) {
		
		super(properties);
	}

        @Override
        @SuppressWarnings("deprecation")
        public void onBlockAdded(BlockState state, World worldIn, BlockPos pos, BlockState oldState, boolean isMoving) {
        
                super.onBlockAdded(state, worldIn, pos, oldState, isMoving);
        
                worldIn.setBlockState(pos, state.with(LIT, Boolean.valueOf(false)), 1);
        }

	public boolean onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit) {
		
		worldIn.setBlockState(pos, state.with(LIT, Boolean.valueOf(true)), 1);  
	}
	
	@OnlyIn(Dist.CLIENT)
	public void animateTick(BlockState stateIn, World worldIn, BlockPos pos, Random rand) {
		
		if (stateIn.get(LIT)) {
				
        	// do stuff
                }
	}

        protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {
        
                builder.add(LIT);
        }
}

 

Edited by MineModder2000
Posted
Just now, MineModder2000 said:

Ah, it's fillStateContainer actually. I am trying to make it do certain animations upon activation only, however nothing inside of my if statement within animateTick is run upon such. I set it to false on block added because its true by default. 

It be better if you posted all of your code unmodified.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Posted
1 minute ago, Animefan8888 said:

It be better if you posted all of your code unmodified.

 

Spoiler

package mymod;

import java.util.Random;

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.FireBlock;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Items;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.world.TickPriority;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

public class Copper extends Block {
	
	public static final BooleanProperty LIT = BlockStateProperties.LIT;

	public Copper(Properties properties) {
		
		super(properties);
	}
	
	@Override
    @SuppressWarnings("deprecation")
	public void onBlockAdded(BlockState state, World worldIn, BlockPos pos, BlockState oldState, boolean isMoving) {
		
	    super.onBlockAdded(state, worldIn, pos, oldState, isMoving);
	    
	    worldIn.setBlockState(pos, state.with(LIT, Boolean.valueOf(false)), 1);
	}
	
	@Override
	public void tick(BlockState state, World worldIn, BlockPos pos, Random random) {
		
		worldIn.setBlockState(pos, state.with(LIT, Boolean.valueOf(true)), 1);
		
		BlockPos blockpos = pos.offset(Direction.UP);
		BlockState blockstate = ((FireBlock)Blocks.FIRE).getStateForPlacement(worldIn, pos);
		
		worldIn.setBlockState(blockpos, blockstate);
		worldIn.getPendingBlockTicks().scheduleTick(pos, this, 180, TickPriority.HIGH);
	}
	
	public boolean onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit) {
		
		if (!player.abilities.allowEdit) {
			 
	        return false;
	    } 
		 
		else {

			if (player.getHeldItemMainhand().getItem() == Items.TORCH) {
				
				worldIn.getPendingBlockTicks().scheduleTick(pos, this, 60, TickPriority.HIGH);
			}
		
	        return true;
	    }
	}
	
	@OnlyIn(Dist.CLIENT)
	public void animateTick(BlockState stateIn, World worldIn, BlockPos pos, Random rand) {
		
		if (stateIn.get(LIT) && rand.nextInt(5) == 0) {  
				
            for(int i = 0; i < rand.nextInt(1) + 1; ++i) {
            		
                worldIn.addParticle(ParticleTypes.LAVA, (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), (double)(rand.nextFloat() / 2.0F), 5.0E-5D, (double)(rand.nextFloat() / 2.0F));
                //worldIn.addParticle(ParticleTypes.LARGE_SMOKE, (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), (double)(rand.nextFloat() / 2.0F), 5.0E-5D, (double)(rand.nextFloat() / 2.0F));
            }
        }
	}
	
	protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {
		
	    builder.add(LIT);
	}
}

 

Posted
14 minutes ago, Animefan8888 said:

You should really read the javadoc of this method.

I did, and I thought I selected the correct int flag : 1. Tried 2 as well, the rest don't seem right. 

 

Spoiler

 /**
    * Sets a block state into this world.Flags are as follows:
    * 1 will cause a block update.
    * 2 will send the change to clients.
    * 4 will prevent the block from being re-rendered.
    * 8 will force any re-renders to run on the main thread instead
    * 16 will prevent neighbor reactions (e.g. fences connecting, observers pulsing).
    * 32 will prevent neighbor reactions from spawning drops.
    * 64 will signify the block is being moved.
    * Flags can be OR-ed
    */

 

Posted
Just now, MineModder2000 said:

  * Flags can be OR-ed

OR-ed means to use the bitwise OR operator. Which would be 3. This will cause a block update which is necessary and send the change to the clients which is needed because animateTick is client only.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Posted
2 minutes ago, Animefan8888 said:

OR-ed means to use the bitwise OR operator. Which would be 3. This will cause a block update which is necessary and send the change to the clients which is needed because animateTick is client only.

3 ain't working honey. 

Posted
2 minutes ago, MineModder2000 said:

3 ain't working honey. 

Then your code is never ran and as such the setBlockState method is never being called. Can you confirm what part of your code is not executing?

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Posted
3 minutes ago, Animefan8888 said:

Then your code is never ran and as such the setBlockState method is never being called. Can you confirm what part of your code is not executing?

I have confirmed that all methods are being called. The if statement inside animateTick gets runs without the check for stateIn.get(LIT). The tick method is definitely called, as my block gets a fire on top of it when activated (after 60 ticks). 

Posted
Just now, MineModder2000 said:

I have confirmed that all methods are being called. The if statement inside animateTick gets runs without the check for stateIn.get(LIT). The tick method is definitely called, as my block gets a fire on top of it when activated (after 60 ticks). 

Post your updated code then.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Posted
17 hours ago, Animefan8888 said:

Post your updated code then.

That's already it, I just changed the 1 to a 3. 

 

Spoiler

package mymod;

import java.util.Random;

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.FireBlock;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Items;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.world.TickPriority;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

public class Copper extends Block {
	
	public static final BooleanProperty LIT = BlockStateProperties.LIT;

	public Copper(Properties properties) {
		
		super(properties);
	}
	
	@Override
    @SuppressWarnings("deprecation")
	public void onBlockAdded(BlockState state, World worldIn, BlockPos pos, BlockState oldState, boolean isMoving) {
		
	    super.onBlockAdded(state, worldIn, pos, oldState, isMoving);
	    
	    worldIn.setBlockState(pos, state.with(LIT, Boolean.valueOf(false)), 3);
	}
	
	@Override
	public void tick(BlockState state, World worldIn, BlockPos pos, Random random) {
		
		worldIn.setBlockState(pos, state.with(LIT, Boolean.valueOf(true)), 3);
		
		BlockPos blockpos = pos.offset(Direction.UP);
		BlockState blockstate = ((FireBlock)Blocks.FIRE).getStateForPlacement(worldIn, pos);
		
		worldIn.setBlockState(blockpos, blockstate);
		worldIn.getPendingBlockTicks().scheduleTick(pos, this, 180, TickPriority.HIGH);
	}
	
	@Override
	public boolean onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit) {
		
		if (!player.abilities.allowEdit) {
			 
	        return false;
	    } 
		 
		else {

			if (player.getHeldItemMainhand().getItem() == Items.TORCH) {
				
				worldIn.getPendingBlockTicks().scheduleTick(pos, this, 60, TickPriority.HIGH);
			}
		
	        return true;
	    }
	}
	
	@Override
	@OnlyIn(Dist.CLIENT)
	public void animateTick(BlockState stateIn, World worldIn, BlockPos pos, Random rand) {
		
		if (stateIn.get(LIT) && rand.nextInt(5) == 0) {  
				
            for(int i = 0; i < rand.nextInt(1) + 1; ++i) {
            		
            	System.out.println("xyz968");
            	
                worldIn.addParticle(ParticleTypes.LAVA, (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), (double)(rand.nextFloat() / 2.0F), 5.0E-5D, (double)(rand.nextFloat() / 2.0F));
                //worldIn.addParticle(ParticleTypes.LARGE_SMOKE, (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), (double)(rand.nextFloat() / 2.0F), 5.0E-5D, (double)(rand.nextFloat() / 2.0F));
            }
        }
	}
	
	@Override
	protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {
		
	    builder.add(LIT);
	}
}

 

 

Posted

So, just a few things (but not related to your issue, just code style problems):

3 hours ago, MineModder2000 said:

Boolean.valueOf(true)

This is copy-pasted decompiled code. There's no reason to use Boolean.valueOf

3 hours ago, MineModder2000 said:

((FireBlock)Blocks.FIRE)

There's no reason for a cast here.

3 hours ago, MineModder2000 said:

player.getHeldItemMainhand()

You are passed a hand in this function, you should query based on the hand given to you.

3 hours ago, MineModder2000 said:

worldIn.getPendingBlockTicks().scheduleTick(pos, this, 180, TickPriority.HIGH);

If the purpose of this code is to continuously set the block above to be fire, there's a better way to do this. Make your block infinitely burnable (like netherack) and set the fire once in onBlockActivated. Then you don't need the tick method or the LIT property at all.

  • Thanks 1

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.

Posted
35 minutes ago, Draco18s said:

So, just a few things (but not related to your issue, just code style problems):

This is copy-pasted decompiled code. There's no reason to use Boolean.valueOf

There's no reason for a cast here.

You are passed a hand in this function, you should query based on the hand given to you.

If the purpose of this code is to continuously set the block above to be fire, there's a better way to do this. Make your block infinitely burnable (like netherack) and set the fire once in onBlockActivated. Then you don't need the tick method or the LIT property at all.

 

  1. Okay I got rid of the Boolean.valueOf. 
  2. The cast is necessary in order for that particular method to be accessible. 
  3. I tried the hand parameter to begin with, but I couldn't see any way to get the held item from it.
  4. Yes, this code is temporary, and I am contemplating even having the block constantly on fire. The reason for the lit property is that I didn't want the block to start throwing particles until it was on fire.
Posted
5 minutes ago, MineModder2000 said:

but I couldn't see any way to get the held item from it.

player.getHeldItem(hand)?

 

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.

Posted
15 minutes ago, MineModder2000 said:

The reason for the lit property is that I didn't want the block to start throwing particles until it was on fire.

World#getBlockState(abovePos).getBlock() some condition to check fire.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Posted
19 minutes ago, Draco18s said:

player.getHeldItem(hand)?

 

Oh duh, I was thinking of starting with handIn and using its methods. This is functionally the same either way, I still changed it though. 

 

10 minutes ago, Animefan8888 said:

World#getBlockState(abovePos).getBlock() some condition to check fire.

This did the trick, however I would still like to know why the other thing didn't work, it bothers me not knowing. Also I may have to do something like that in the future. 

Posted
42 minutes ago, MineModder2000 said:

however I would still like to know why the other thing didn't work

Have you run through your code with your IDE's debugger? What about using the f3 menu/gui to look at the blocks state?

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Posted
10 minutes ago, Animefan8888 said:

Have you run through your code with your IDE's debugger? What about using the f3 menu/gui to look at the blocks state?

I'll do this. I want to also know how to alter a block's color / texture without changing it's state, if possible. 

Posted
1 minute ago, MineModder2000 said:

 I want to also know how to alter a block's color / texture without changing it's state, if possible.

Not without rendering it every frame with a TESR. Changing its state is the only way to force the chunk to recreate its mesh and push it to the GPU.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

I will be posting 1.15.2 modding tutorials on this channel. If you want to be notified of it do the normal YouTube stuff like subscribing, ect.

Forge and vanilla BlockState generator.

Posted
15 hours ago, Animefan8888 said:

Not without rendering it every frame with a TESR. Changing its state is the only way to force the chunk to recreate its mesh and push it to the GPU.

I see, I'll just make two blocks instead, much easier and better for my purposes. Anyways back to the boolean property, I figured out the issue. The line : worldIn.setBlockState(pos, state.with(LIT, true), 3); in the tick method doesn't set the value to true, as confirmed by println. So whatever value it's set to in the onBlockAdded method, is what it stays as. Hence the reason the if statement check in the animateTick method fails....

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.