Jump to content

Recommended Posts

Posted

i still have troubles creating a functional tile entity

 

the Error log i´m getting is this:

 

A TileEntity type me.spawntweak.lists.MobSpawnerTileEntity has thrown an exception trying to write state. It will not persist, Report this to the mod author java.lang.RuntimeException: class me.spawntweak.lists.MobSpawnerTileEntity is missing a mapping

 

[02:29:55] [Server thread/ERROR] [minecraft/Chunk]: A TileEntity type fabian.spawntweak.lists.MobSpawnerTileEntity has thrown an exception trying to write state. It will not persist, Report this to the mod author java.lang.RuntimeException: class me.spawntweak.lists.MobSpawnerTileEntity is missing a mapping! This is a bug!         at net.minecraft.tileentity.TileEntity.writeInternal(TileEntity.java:72) ~[?:?] {re:classloading}         at net.minecraft.tileentity.TileEntity.write(TileEntity.java:66) ~[?:?] {re:classloading}         at me.spawntweak.lists.MobSpawnerTileEntity.write(MobSpawnerTileEntity.java:72) ~[?:?] {re:classloading}         at net.minecraft.world.chunk.Chunk.func_223134_j(Chunk.java:444) ~[?:?] {re:classloading}         at net.minecraft.world.chunk.storage.ChunkSerializer.write(ChunkSerializer.java:303) ~[?:?] {re:classloading}         at net.minecraft.world.server.ChunkManager.func_219229_a(ChunkManager.java:677) ~[?:?] {re:classloading}         at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174) [?:1.8.0_241] {}         at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175) [?:1.8.0_241] {}         at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) [?:1.8.0_241] {}         at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382) [?:1.8.0_241] {}         at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482) [?:1.8.0_241] {}         at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472) [?:1.8.0_241] {}         at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151) [?:1.8.0_241] {}         at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174) [?:1.8.0_241] {}         at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) [?:1.8.0_241] {}         at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418) [?:1.8.0_241] {}         at net.minecraft.world.server.ChunkManager.save(ChunkManager.java:336) [?:?] {re:classloading}         at net.minecraft.world.server.ServerChunkProvider.save(ServerChunkProvider.java:309) [?:?] {re:classloading,pl:accesstransformer:B}         at net.minecraft.world.server.ServerWorld.save(ServerWorld.java:770) [?:?] {re:classloading}         at net.minecraft.server.MinecraftServer.save(MinecraftServer.java:528) [?:?] {re:classloading,pl:accesstransformer:B}         at net.minecraft.server.MinecraftServer.stopServer(MinecraftServer.java:571) [?:?] {re:classloading,pl:accesstransformer:B}         at net.minecraft.server.integrated.IntegratedServer.stopServer(IntegratedServer.java:235) [?:?] {re:classloading,pl:runtimedistcleaner:A}         at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:685) [?:?] {re:classloading,pl:accesstransformer:B}         at java.lang.Thread.run(Thread.java:748) [?:1.8.0_241] {}

main:

@Mod("spawntweak")
public class SpawnTweak{

    
    public static SpawnTweak instance;
    public static final String modid = "spawntweak";
    private static final Logger logger = LogManager.getLogger(modid);
    
    public SpawnTweak() {
        instance=this;
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::clientRegistries);
        MinecraftForge.EVENT_BUS.register(this);
        
        
        }
    
private void setup(final FMLCommonSetupEvent event) {
        
        logger.info("setup registered");
        
    }
    private void clientRegistries(final FMLClientSetupEvent event) {
        
        logger.info("client registered");
        
    }
    
    @Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD)
    public static class RegistryEvents{
        
        

        @SubscribeEvent
        public static void registerItems(final RegistryEvent.Register<Item> event) {
            event.getRegistry().registerAll(
                    ItemList.spawner= new BlockItem(BlockList.spawner, new Item.Properties().group(ItemGroup.TRANSPORTATION)).setRegistryName(BlockList.spawner.getRegistryName()));}

        @SubscribeEvent
        public static void registerBlocks(final RegistryEvent.Register<Block> event) {
            event.getRegistry().registerAll(
            
            BlockList.spawner = new MobSpawner(MobSpawner.Properties.create(Material.IRON).hardnessAndResistance(3.0f, 3.0f).sound(SoundType.METAL)).setRegistryName("minecraft:spawner"));
            logger.info("Blocks registered");
        }

        
        @SubscribeEvent
        public static void registerTileEntety(RegistryEvent.Register<TileEntityType<?>> event) {

            
         TileEntityType<?> type = TileEntityType.Builder.create(MobSpawnerTileEntity::new, BlockList.spawner).build(null);
          type.setRegistryName("minecraft:mob_spawner");
          event.getRegistry().register(type);
        }
   
    }    
        
    }    

Block

public class MobSpawner extends Block{
    
    
    public MobSpawner(Properties properties) {
        super(Properties.create(Material.IRON).hardnessAndResistance(3.0f, 3.0f).sound(SoundType.METAL));
      
    }
   
    @Override
    public TileEntity createTileEntity(BlockState state, IBlockReader world) {
        return new MobSpawnerTileEntity();
    }
    public BlockRenderLayer getRenderLayer()
    {
        return BlockRenderLayer.TRANSLUCENT;
    }
    
    @Override
    public boolean hasTileEntity(BlockState state) {
        return true;
    }

}

Tile Entity

public class MobSpawnerTileEntity extends TileEntity implements ITickableTileEntity {
   private final AbstractSpawner spawnerLogic = new AbstractSpawner() {
      public void broadcastEvent(int id) {
         MobSpawnerTileEntity.this.world.addBlockEvent(MobSpawnerTileEntity.this.pos, Blocks.SPAWNER, id, 0);
      }

      public World getWorld() {
         return MobSpawnerTileEntity.this.world;
      }

      public BlockPos getSpawnerPosition() {
         return MobSpawnerTileEntity.this.pos;
      }

      public void setNextSpawnData(WeightedSpawnerEntity nextSpawnData) {
         super.setNextSpawnData(nextSpawnData);
         if (this.getWorld() != null) {
            BlockState blockstate = this.getWorld().getBlockState(this.getSpawnerPosition());
            this.getWorld().notifyBlockUpdate(MobSpawnerTileEntity.this.pos, blockstate, blockstate, 4);
         }

      }
   };
   
   public void tick(BlockState state, World worldIn, BlockPos pos, Random random) {
          if (!worldIn.isRemote) {
             if (worldIn.isBlockPowered(pos)) {
                AbstractSpawner.isActivated  = true;
           }
             else 
        {
            AbstractSpawner.isActivated =false;     
                 
                 
                 
        }  
       }

    
    
     }
   
   public MobSpawnerTileEntity() {
      super(TileEntityType.MOB_SPAWNER);
   }

   public void read(CompoundNBT compound) {
      super.read(compound);
      this.spawnerLogic.read(compound);
   }

   public CompoundNBT write(CompoundNBT compound) {
      super.write(compound);
      this.spawnerLogic.write(compound);
      return compound;
   }

   public void tick() {
      this.spawnerLogic.tick();
   }

  
   @Nullable
   public SUpdateTileEntityPacket getUpdatePacket() {
      return new SUpdateTileEntityPacket(this.pos, 1, this.getUpdateTag());
   }

  
   public CompoundNBT getUpdateTag() {
      CompoundNBT compoundnbt = this.write(new CompoundNBT());
      compoundnbt.remove("SpawnPotentials");
      return compoundnbt;
   }

 
   public boolean receiveClientEvent(int id, int type) {
      return this.spawnerLogic.setDelayToMin(id) ? true : super.receiveClientEvent(id, type);
   }

 
   public boolean onlyOpsCanSetNbt() {
      return true;
   }

   public AbstractSpawner getSpawnerBaseLogic() {
      return this.spawnerLogic;
   }
}

Abstract Spawner

public abstract class AbstractSpawner {
   private static final Logger LOGGER = LogManager.getLogger();
   public static boolean isActivated;
   private int spawnDelay = 20;
   private final List<WeightedSpawnerEntity> potentialSpawns = Lists.newArrayList();
   private WeightedSpawnerEntity spawnData = new WeightedSpawnerEntity();
   private double mobRotation;
   private double prevMobRotation;
   private int minSpawnDelay = 200;
   private int maxSpawnDelay = 800;
   private int spawnCount = 4;
   private Entity cachedEntity;
   private int maxNearbyEntities = 6;
   private int activatingRangeFromPlayer = 16;
   private int spawnRange = 4;

   @SuppressWarnings("resource")
@Nullable
   private ResourceLocation getEntityId() {
      String s = this.spawnData.getNbt().getString("id");

      try {
         return StringUtils.isNullOrEmpty(s) ? null : new ResourceLocation(s);
      } catch (ResourceLocationException var4) {
         BlockPos blockpos = this.getSpawnerPosition();
         LOGGER.warn("Invalid entity id '{}' at spawner {}:[{},{},{}]", s, this.getWorld().dimension.getType(), blockpos.getX(), blockpos.getY(), blockpos.getZ());
         return null;
      }
   }

   @SuppressWarnings("deprecation")
public void setEntityType(EntityType<?> type) {
      this.spawnData.getNbt().putString("id", Registry.ENTITY_TYPE.getKey(type).toString());
   }

   /**
    * Returns true if there's a player close enough to this mob spawner to activate it.
    */
   public boolean isActivated() {
      BlockPos blockpos = this.getSpawnerPosition();
      return this.getWorld().isPlayerWithin((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D, (double)this.activatingRangeFromPlayer);
   }

   public void tick() {
      
      if (!this.isActivated()||!isActivated) {
         this.prevMobRotation = this.mobRotation;
      } else {
         World world = this.getWorld();
         BlockPos blockpos = this.getSpawnerPosition();
         if (world.isRemote) {
            double d3 = (double)((float)blockpos.getX() + world.rand.nextFloat());
            double d4 = (double)((float)blockpos.getY() + world.rand.nextFloat());
            double d5 = (double)((float)blockpos.getZ() + world.rand.nextFloat());
            world.addParticle(ParticleTypes.SMOKE, d3, d4, d5, 0.0D, 0.0D, 0.0D);
            world.addParticle(ParticleTypes.FLAME, d3, d4, d5, 0.0D, 0.0D, 0.0D);
            if (this.spawnDelay > 0) {
               --this.spawnDelay;
            }

            this.prevMobRotation = this.mobRotation;
            this.mobRotation = (this.mobRotation + (double)(1000.0F / ((float)this.spawnDelay + 200.0F))) % 360.0D;
         } else {
            if (this.spawnDelay == -1) {
               this.resetTimer();
            }

            if (this.spawnDelay > 0) {
               --this.spawnDelay;
               return;
            }

            boolean flag = false;

            for(int i = 0; i < this.spawnCount; ++i) {
               CompoundNBT compoundnbt = this.spawnData.getNbt();
               Optional<EntityType<?>> optional = EntityType.readEntityType(compoundnbt);
               if (!optional.isPresent()) {
                  this.resetTimer();
                  return;
               }

               ListNBT listnbt = compoundnbt.getList("Pos", 6);
               int j = listnbt.size();
               double d0 = j >= 1 ? listnbt.getDouble(0) : (double)blockpos.getX() + (world.rand.nextDouble() - world.rand.nextDouble()) * (double)this.spawnRange + 0.5D;
               double d1 = j >= 2 ? listnbt.getDouble(1) : (double)(blockpos.getY() + world.rand.nextInt(3) - 1);
               double d2 = j >= 3 ? listnbt.getDouble(2) : (double)blockpos.getZ() + (world.rand.nextDouble() - world.rand.nextDouble()) * (double)this.spawnRange + 0.5D;
               if (world.areCollisionShapesEmpty(optional.get().func_220328_a(d0, d1, d2)) && EntitySpawnPlacementRegistry.func_223515_a(optional.get(), world.getWorld(), SpawnReason.SPAWNER, new BlockPos(d0, d1, d2), world.getRandom())) {
                  Entity entity = EntityType.func_220335_a(compoundnbt, world, (p_221408_6_) -> {
                     p_221408_6_.setLocationAndAngles(d0, d1, d2, p_221408_6_.rotationYaw, p_221408_6_.rotationPitch);
                     return p_221408_6_;
                  });
                  if (entity == null) {
                     this.resetTimer();
                     return;
                  }

                  int k = world.getEntitiesWithinAABB(entity.getClass(), (new AxisAlignedBB((double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ(), (double)(blockpos.getX() + 1), (double)(blockpos.getY() + 1), (double)(blockpos.getZ() + 1))).grow((double)this.spawnRange)).size();
                  if (k >= this.maxNearbyEntities) {
                     this.resetTimer();
                     return;
                  }

                  entity.setLocationAndAngles(entity.posX, entity.posY, entity.posZ, world.rand.nextFloat() * 360.0F, 0.0F);
                  if (entity instanceof MobEntity) {
                     MobEntity mobentity = (MobEntity)entity;
                     if (!EventFactory.canEntitySpawnSpawner(mobentity, world, (float)entity.posX, (float)entity.posY, (float)entity.posZ, this)) {
                        continue;
                     }

                     if (this.spawnData.getNbt().size() == 1 && this.spawnData.getNbt().contains("id", 8)) {
                        ((MobEntity)entity).onInitialSpawn(world, world.getDifficultyForLocation(new BlockPos(entity)), SpawnReason.SPAWNER, (ILivingEntityData)null, (CompoundNBT)null);
                     }
                  }

                  this.func_221409_a(entity);
                  world.playEvent(2004, blockpos, 0);
                  if (entity instanceof MobEntity) {
                     ((MobEntity)entity).spawnExplosionParticle();
                  }

                  flag = true;
               }
            }

            if (flag) {
               this.resetTimer();
            }
         }

      }
   }

   private void func_221409_a(Entity p_221409_1_) {
      if (this.getWorld().addEntity(p_221409_1_)) {
         for(Entity entity : p_221409_1_.getPassengers()) {
            this.func_221409_a(entity);
         }

      }
   }

   @SuppressWarnings("resource")
private void resetTimer() {
      if (this.maxSpawnDelay <= this.minSpawnDelay) {
         this.spawnDelay = this.minSpawnDelay;
      } else {
         int i = this.maxSpawnDelay - this.minSpawnDelay;
         this.spawnDelay = this.minSpawnDelay + this.getWorld().rand.nextInt(i);
      }

      if (!this.potentialSpawns.isEmpty()) {
         this.setNextSpawnData(WeightedRandom.getRandomItem(this.getWorld().rand, this.potentialSpawns));
      }

      this.broadcastEvent(1);
   }

   @SuppressWarnings("resource")
public void read(CompoundNBT nbt) {
      this.spawnDelay = nbt.getShort("Delay");
      this.potentialSpawns.clear();
      if (nbt.contains("SpawnPotentials", 9)) {
         ListNBT listnbt = nbt.getList("SpawnPotentials", 10);

         for(int i = 0; i < listnbt.size(); ++i) {
            this.potentialSpawns.add(new WeightedSpawnerEntity(listnbt.getCompound(i)));
         }
      }

      if (nbt.contains("SpawnData", 10)) {
         this.setNextSpawnData(new WeightedSpawnerEntity(1, nbt.getCompound("SpawnData")));
      } else if (!this.potentialSpawns.isEmpty()) {
         this.setNextSpawnData(WeightedRandom.getRandomItem(this.getWorld().rand, this.potentialSpawns));
      }

      if (nbt.contains("MinSpawnDelay", 99)) {
         this.minSpawnDelay = nbt.getShort("MinSpawnDelay");
         this.maxSpawnDelay = nbt.getShort("MaxSpawnDelay");
         this.spawnCount = nbt.getShort("SpawnCount");
      }

      if (nbt.contains("MaxNearbyEntities", 99)) {
         this.maxNearbyEntities = nbt.getShort("MaxNearbyEntities");
         this.activatingRangeFromPlayer = nbt.getShort("RequiredPlayerRange");
      }

      if (nbt.contains("SpawnRange", 99)) {
         this.spawnRange = nbt.getShort("SpawnRange");
      }

      if (this.getWorld() != null) {
         this.cachedEntity = null;
      }

   }

   public CompoundNBT write(CompoundNBT compound) {
      ResourceLocation resourcelocation = this.getEntityId();
      if (resourcelocation == null) {
         return compound;
      } else {
         compound.putShort("Delay", (short)this.spawnDelay);
         compound.putShort("MinSpawnDelay", (short)this.minSpawnDelay);
         compound.putShort("MaxSpawnDelay", (short)this.maxSpawnDelay);
         compound.putShort("SpawnCount", (short)this.spawnCount);
         compound.putShort("MaxNearbyEntities", (short)this.maxNearbyEntities);
         compound.putShort("RequiredPlayerRange", (short)this.activatingRangeFromPlayer);
         compound.putShort("SpawnRange", (short)this.spawnRange);
         compound.put("SpawnData", this.spawnData.getNbt().copy());
         ListNBT listnbt = new ListNBT();
         if (this.potentialSpawns.isEmpty()) {
            listnbt.add(this.spawnData.toCompoundTag());
         } else {
            for(WeightedSpawnerEntity weightedspawnerentity : this.potentialSpawns) {
               listnbt.add(weightedspawnerentity.toCompoundTag());
            }
         }

         compound.put("SpawnPotentials", listnbt);
         return compound;
      }
   }

   @OnlyIn(Dist.CLIENT)
   public Entity getCachedEntity() {
      if (this.cachedEntity == null) {
         this.cachedEntity = EntityType.func_220335_a(this.spawnData.getNbt(), this.getWorld(), Function.identity());
         if (this.spawnData.getNbt().size() == 1 && this.spawnData.getNbt().contains("id", 8) && this.cachedEntity instanceof MobEntity) {
            ((MobEntity)this.cachedEntity).onInitialSpawn(this.getWorld(), this.getWorld().getDifficultyForLocation(new BlockPos(this.cachedEntity)), SpawnReason.SPAWNER, (ILivingEntityData)null, (CompoundNBT)null);
         }
      }

      return this.cachedEntity;
   }

   /**
    * Sets the delay to minDelay if parameter given is 1, else return false.
    */
   public boolean setDelayToMin(int delay) {
      if (delay == 1 && this.getWorld().isRemote) {
         this.spawnDelay = this.minSpawnDelay;
         return true;
      } else {
         return false;
      }
   }

   public void setNextSpawnData(WeightedSpawnerEntity nextSpawnData) {
      this.spawnData = nextSpawnData;
   }

   public abstract void broadcastEvent(int id);

   public abstract World getWorld();

   public abstract BlockPos getSpawnerPosition();

   @OnlyIn(Dist.CLIENT)
   public double getMobRotation() {
      return this.mobRotation;
   }

   @OnlyIn(Dist.CLIENT)
   public double getPrevMobRotation() {
      return this.prevMobRotation;
   }

   @Nullable
   public Entity getSpawnerEntity() {
      return null;
   }
}

    

Posted

The reason this error is happening is that you are using the old TileEntityType in your TileEntity constructor instead of the newly registered one. When creating the new TileEntityType store it in a public static final field and use that instead of the old one.

Posted
1 hour ago, CHEESEBOT314 said:

When creating the new TileEntityType store it in a public static final field and use that instead of the old one.

Or better still, use ObjectHolder or DeferredRegistry. There are plenty of topics on both if you search this site.

Posted
2 hours ago, CHEESEBOT314 said:

The reason this error is happening is that you are using the old TileEntityType in your TileEntity constructor instead of the newly registered one. When creating the new TileEntityType store it in a public static final field and use that instead of the old one.

i have now done this

 

    
         TileEntityType<?> type = TileEntityType.Builder.create(MobSpawnerTileEntity::new, BlockList.spawner).build(null);
          type.setRegistryName("minecraft:mob_spawner");
          event.getRegistry().register(type);
          TEList.mob_spawner = type;

 

and in the tile entity class done this

 

TileEntityType.MOB_SPAWNER ==> TEList.mob_spawner

and now the game neither crashes nor spews out error messages and now the entity is registered, but the tile entity doesn´t work as excpected. instead of behaving like the vanilla spawner (i used the vanilla code for spawners and added

public void tick(BlockState state, World worldIn, BlockPos pos, Random random) {
          if (!worldIn.isRemote) {
             if (worldIn.isBlockPowered(pos)) {
                AbstractSpawner.isActivated  = true;
           }
             else 
        {
            AbstractSpawner.isActivated =false;     
                 
                 
                 
        }  
       }

    
    
     }) but it behaves lika a normal block even when i comment the changes out. also no errors are shown

Posted
4 minutes ago, DarkAssassin said:

public void tick(BlockState state, World worldIn, BlockPos pos, Random random) {
          if (!worldIn.isRemote) {
             if (worldIn.isBlockPowered(pos)) {
                AbstractSpawner.isActivated  = true;
           }
             else 
        {
            AbstractSpawner.isActivated =false;     
                 
                 
                 
        }  
       }

    
    
     }

You probably need to call super#tick at some point.

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.