Résolu Faire un compteur de tick (Bar de soif)
-
Je dois donc mettre TickEvent.ServerTickEvent, mais à la place ou en plus de TickEvent.PlayerTickEvent ?
-
Non.
Il faut que tu d’endroit ta fonction MinecraftForge.EVENT_BUS.register(new nomdetaclasseaveclesevent()) car actuellement elle se trouve à un endroit client only. -
Désolé mais je comprends pas le message : “Il faut que tu d’endroit ta fonction”, moi dans ma classe principale j’ai ça :
@EventHandler public void init (FMLInitializationEvent event) { proxy.registerRenders(); ThirstCapabilities.register(); MinecraftForge.EVENT_BUS.register(new SurvivantBlockEvent()); MinecraftForge.EVENT_BUS.register(new SurvivantThirstBar()); /**Classe avec les events concernés*/ EntityHandler.RegisterFish(EntityFish.class, "Fish"); EntityHandler.RegisterSalmon(EntitySalmon.class, "Salmon"); EntityHandler.RegisterRay(EntityRay.class, "Ray"); }
Merci d’avance.
-
Hum, c’est bien enregistré côté client et serveur.
Ça bloque autre-part alors.
Tu peux envoyer la classe SurvivantThirstBar complète ? -
Voici la classe SurvivantThirstBar :
package com.survivant.mod; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.DamageSource; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.GuiScreenEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; public class SurvivantThirstBar { public static int i = 0; @SubscribeEvent public void playerTick(TickEvent.PlayerTickEvent event) { if (event.player.hasCapability(ModSurvivant.T_CAP, null)) { ThirstCapabilities cap = event.player.getCapability(ModSurvivant.T_CAP, null); if (!event.player.capabilities.isCreativeMode) { if (cap.getThirstVal() > 0) { i++; if (i == 250) { cap.setThirstVal(cap.getThirstVal()-1); i = 0; } } else { cap.setThirstVal(0); event.player.attackEntityFrom(ModSurvivant.damageSourceDehydration, 1.0F); System.out.println(event.player.worldObj.isRemote); } } } } @SubscribeEvent public void onPlayerCloned(PlayerEvent.Clone event) { if (event.wasDeath) { if (event.original.hasCapability(ModSurvivant.T_CAP, null)) { ThirstCapabilities cap = event.original.getCapability(ModSurvivant.T_CAP, null); cap.setThirstVal(86); ThirstCapabilities newCap = event.entityPlayer.getCapability(ModSurvivant.T_CAP, null); newCap.setThirstVal(cap.getThirstVal()); } } } @SubscribeEvent public void onPlayerRespawn(PlayerRespawnEvent event) { if(!event.player.worldObj.isRemote) { event.player.getCapability(ModSurvivant.T_CAP, null).sync(); } } @SubscribeEvent public void onAttachCapability(AttachCapabilitiesEvent.Entity event) { if (event.getEntity() instanceof EntityPlayer) { event.addCapability(new ResourceLocation(Reference.MOD_ID + ":T_CAP"), new ThirstCapabilities((EntityPlayer) event.getEntity())); } } @SubscribeEvent public void onRenderGameOverlay(RenderGameOverlayEvent event) { if (!event.isCancelable() && event.type == ElementType.EXPERIENCE) { Minecraft mc = Minecraft.getMinecraft(); if (!mc.thePlayer.capabilities.isCreativeMode) { ThirstCapabilities cap = mc.thePlayer.getCapability(ModSurvivant.T_CAP, null); int posX = event.resolution.getScaledWidth() / 2 + 7; int posY = event.resolution.getScaledHeight() - 50; mc.renderEngine.bindTexture(new ResourceLocation("survivant:textures/gui/thirstBar.png")); mc.ingameGUI.drawTexturedModalRect(posX, posY, 0, 0, 88, 9); mc.ingameGUI.drawTexturedModalRect(posX + 1, posY + 1, 0, 9, cap.getThirstVal(), 7); } } } }
-
Je ne comprends pas pourquoi ta fonction n’est que appelé côté client.
Ce n’est pas normal.Tu peux envoyer un zip de ton dossier src pour que je puisse regarder en détail ?
-
Voilà :
-
Désolé du temps de réponse, j’avais complètement oublié.
Il avait des npe dans la console en rapport avec le chargement du nbt du joueur, causé par ta capabilité. Dans ThirstCapabilities.java :@Override public NBTTagCompound serializeNBT() { NBTTagCompound compound = new NBTTagCompound(); compound.setInteger("ThirstVal", this.getThirstVal()); return null; }
devrait être :
@Override public NBTTagCompound serializeNBT() { NBTTagCompound compound = new NBTTagCompound(); compound.setInteger("ThirstVal", this.getThirstVal()); return compound; }
Et c’est tout ce que j’ai eu besoin de changer. Le joueur prend bien des dégâts ensuite.
-
Je ne comprends pas, ça ne veut pas fonctionner. Voilà ce que met la console maintenant :
2017-04-21 14:37:33,411 WARN Unable to instantiate org.fusesource.jansi.WindowsAnsiOutputStream 2017-04-21 14:37:33,416 WARN Unable to instantiate org.fusesource.jansi.WindowsAnsiOutputStream [14:37:33] [main/INFO] [GradleStart]: Extra: [] [14:37:33] [main/INFO] [GradleStart]: Running with arguments: [–userProperties, {}, --assetsDir, C:/Users/user/.gradle/caches/minecraft/assets, --assetIndex, 1.8, --accessToken{REDACTED}, --version, 1.8.9, --tweakClass, net.minecraftforge.fml.common.launcher.FMLTweaker, --tweakClass, net.minecraftforge.gradle.tweakers.CoremodTweaker] [14:37:33] [main/INFO] [LaunchWrapper]: Loading tweak class name net.minecraftforge.fml.common.launcher.FMLTweaker [14:37:33] [main/INFO] [LaunchWrapper]: Using primary tweak class name net.minecraftforge.fml.common.launcher.FMLTweaker [14:37:33] [main/INFO] [LaunchWrapper]: Loading tweak class name net.minecraftforge.gradle.tweakers.CoremodTweaker [14:37:33] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.common.launcher.FMLTweaker [14:37:33] [main/INFO] [FML]: Forge Mod Loader version 11.15.1.1747 for Minecraft 1.8.9 loading [14:37:33] [main/INFO] [FML]: Java is Java HotSpot(TM) 64-Bit Server VM, version 1.8.0_121, running on Windows 8.1:amd64:6.3, installed at C:\Program Files\Java\jre1.8.0_121 [14:37:33] [main/INFO] [FML]: Managed to load a deobfuscated Minecraft name- we are in a deobfuscated environment. Skipping runtime deobfuscation [14:37:33] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.gradle.tweakers.CoremodTweaker [14:37:33] [main/INFO] [GradleStart]: Injecting location in coremod net.minecraftforge.fml.relauncher.FMLCorePlugin [14:37:33] [main/INFO] [GradleStart]: Injecting location in coremod net.minecraftforge.classloading.FMLForgePlugin [14:37:33] [main/INFO] [LaunchWrapper]: Loading tweak class name net.minecraftforge.fml.common.launcher.FMLInjectionAndSortingTweaker [14:37:33] [main/INFO] [LaunchWrapper]: Loading tweak class name net.minecraftforge.fml.common.launcher.FMLDeobfTweaker [14:37:33] [main/INFO] [LaunchWrapper]: Loading tweak class name net.minecraftforge.gradle.tweakers.AccessTransformerTweaker [14:37:33] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.common.launcher.FMLInjectionAndSortingTweaker [14:37:33] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.common.launcher.FMLInjectionAndSortingTweaker [14:37:33] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.relauncher.CoreModManager$FMLPluginWrapper [14:37:33] [main/ERROR] [FML]: The binary patch set is missing. Either you are in a development environment, or things are not going to work! [14:37:35] [main/ERROR] [FML]: FML appears to be missing any signature data. This is not a good thing [14:37:35] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.relauncher.CoreModManager$FMLPluginWrapper [14:37:35] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.common.launcher.FMLDeobfTweaker [14:37:36] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.gradle.tweakers.AccessTransformerTweaker [14:37:36] [main/INFO] [LaunchWrapper]: Loading tweak class name net.minecraftforge.fml.common.launcher.TerminalTweaker [14:37:36] [main/INFO] [LaunchWrapper]: Calling tweak class net.minecraftforge.fml.common.launcher.TerminalTweaker [14:37:36] [main/INFO] [LaunchWrapper]: Launching wrapped minecraft {net.minecraft.client.main.Main} 2017-04-21 14:37:37,641 WARN Unable to instantiate org.fusesource.jansi.WindowsAnsiOutputStream 2017-04-21 14:37:37,725 WARN Unable to instantiate org.fusesource.jansi.WindowsAnsiOutputStream 2017-04-21 14:37:37,731 WARN Unable to instantiate org.fusesource.jansi.WindowsAnsiOutputStream [14:37:38] [Client thread/INFO]: Setting user: Player193 [14:37:44] [Client thread/INFO]: LWJGL Version: 2.9.4 [14:37:45] [Client thread/WARN] [FML]: ============================================================= [14:37:45] [Client thread/WARN] [FML]: MOD HAS DIRECT REFERENCE System.exit() THIS IS NOT ALLOWED REROUTING TO FML! [14:37:45] [Client thread/WARN] [FML]: Offendor: com/sun/jna/Native.main([Ljava/lang/String;)V [14:37:45] [Client thread/WARN] [FML]: Use FMLCommonHandler.exitJava instead [14:37:45] [Client thread/WARN] [FML]: ============================================================= [14:37:46] [Client thread/INFO] [STDOUT]: [net.minecraftforge.fml.client.SplashProgress:start:246]: –-- Minecraft Crash Report ---- // Hi. I'm Minecraft, and I'm a crashaholic. Time: 21/04/17 14:37 Description: Loading screen debug info This is just a prompt for computer specs to be printed. THIS IS NOT A ERROR A detailed walkthrough of the error, its code path and all known details is as follows: --------------------------------------------------------------------------------------- -- System Details -- Details: Minecraft Version: 1.8.9 Operating System: Windows 8.1 (amd64) version 6.3 Java Version: 1.8.0_121, Oracle Corporation Java VM Version: Java HotSpot(TM) 64-Bit Server VM (mixed mode), Oracle Corporation Memory: 764710904 bytes (729 MB) / 1038876672 bytes (990 MB) up to 1038876672 bytes (990 MB) JVM Flags: 3 total; -Xincgc -Xmx1024M -Xms1024M IntCache: cache: 0, tcache: 0, allocated: 0, tallocated: 0 FML: Loaded coremods (and transformers): GL info: ' Vendor: 'Intel' Version: '4.0.0 - Build 10.18.10.3621' Renderer: 'Intel(R) HD Graphics 4000' [14:37:46] [Client thread/INFO] [FML]: MinecraftForge v11.15.1.1747 Initialized [14:37:46] [Client thread/INFO] [FML]: Replaced 204 ore recipies [14:37:47] [Client thread/INFO] [FML]: Found 0 mods from the command line. Injecting into mod discoverer [14:37:47] [Client thread/INFO] [FML]: Searching C:\Users\user\Desktop\forge-1.8.9-11.15.1.1747-mdk\run\mods for mods [14:37:51] [Client thread/INFO] [FML]: Forge Mod Loader has identified 4 mods to load [14:37:51] [Client thread/INFO] [FML]: Attempting connection with missing mods [mcp, FML, Forge, survivant] at CLIENT [14:37:51] [Client thread/INFO] [FML]: Attempting connection with missing mods [mcp, FML, Forge, survivant] at SERVER [14:37:52] [Client thread/INFO]: Reloading ResourceManager: Default, FMLFileResourcePack:Forge Mod Loader, FMLFileResourcePack:Minecraft Forge, FMLFileResourcePack:Mod Survivant [14:37:52] [Client thread/INFO] [FML]: Processing ObjectHolder annotations [14:37:52] [Client thread/INFO] [FML]: Found 384 ObjectHolder annotations [14:37:52] [Client thread/INFO] [FML]: Identifying ItemStackHolder annotations [14:37:52] [Client thread/INFO] [FML]: Found 0 ItemStackHolder annotations [14:37:53] [Client thread/INFO] [FML]: Configured a dormant chunk cache size of 0 [14:37:53] [Forge Version Check/INFO] [ForgeVersionCheck]: [Forge] Starting version check at http://files.minecraftforge.net/maven/net/minecraftforge/forge/promotions_slim.json [14:37:53] [Forge Version Check/INFO] [ForgeVersionCheck]: [Forge] Found status: OUTDATED Target: 11.15.1.1902 [14:37:53] [Client thread/INFO] [FML]: Applying holder lookups [14:37:53] [Client thread/INFO] [FML]: Holder lookups applied [14:37:53] [Client thread/INFO] [FML]: Injecting itemstacks [14:37:53] [Client thread/INFO] [FML]: Itemstack injection complete [14:37:54] [Sound Library Loader/INFO]: Starting up SoundSystem… [14:37:54] [Thread-9/INFO]: Initializing LWJGL OpenAL [14:37:54] [Thread-9/INFO]: (The LWJGL binding of OpenAL. For more information, see http://www.lwjgl.org) [14:37:54] [Thread-9/INFO]: OpenAL initialized. [14:37:54] [Sound Library Loader/INFO]: Sound engine started [14:38:02] [Client thread/INFO] [FML]: Max texture size: 8192 [14:38:02] [Client thread/INFO]: Created: 16x16 textures-atlas [14:38:03] [Client thread/ERROR] [FML]: Model definition for location survivant:blockBanana#inventory not found [14:38:03] [Client thread/ERROR] [FML]: Model definition for location survivant:blockCoconut#inventory not found [14:38:05] [Client thread/INFO] [FML]: Injecting itemstacks [14:38:05] [Client thread/INFO] [FML]: Itemstack injection complete [14:38:05] [Client thread/INFO] [FML]: Forge Mod Loader has successfully loaded 4 mods [14:38:05] [Client thread/INFO]: Reloading ResourceManager: Default, FMLFileResourcePack:Forge Mod Loader, FMLFileResourcePack:Minecraft Forge, FMLFileResourcePack:Mod Survivant [14:38:05] [Client thread/INFO]: SoundSystem shutting down… [14:38:05] [Client thread/WARN]: Author: Paul Lamb, www.paulscode.com [14:38:05] [Sound Library Loader/INFO]: Starting up SoundSystem… [14:38:05] [Thread-11/INFO]: Initializing LWJGL OpenAL [14:38:05] [Thread-11/INFO]: (The LWJGL binding of OpenAL. For more information, see http://www.lwjgl.org) [14:38:05] [Thread-11/INFO]: OpenAL initialized. [14:38:06] [Sound Library Loader/INFO]: Sound engine started [14:38:11] [Client thread/INFO] [FML]: Max texture size: 8192 [14:38:12] [Client thread/INFO]: Created: 512x512 textures-atlas [14:38:12] [Client thread/ERROR] [FML]: Model definition for location survivant:blockBanana#inventory not found [14:38:12] [Client thread/ERROR] [FML]: Model definition for location survivant:blockCoconut#inventory not found [14:38:14] [Realms Notification Availability checker #1/INFO]: Could not authorize you against Realms server: Invalid session id [14:38:37] [Realms Notification Availability checker #1/INFO]: Could not authorize you against Realms server: Invalid session id [14:38:37] [Server thread/INFO]: Starting integrated minecraft server version 1.8.9 [14:38:37] [Server thread/INFO]: Generating keypair [14:38:37] [Server thread/INFO] [FML]: Injecting existing block and item data into this server instance [14:38:37] [Server thread/INFO] [FML]: Applying holder lookups [14:38:37] [Server thread/INFO] [FML]: Holder lookups applied [14:38:38] [Server thread/INFO] [FML]: Loading dimension 0 (Nouveau monde) (net.minecraft.server.integrated.IntegratedServer@2edd88d1) [14:38:38] [Server thread/INFO] [FML]: Loading dimension 1 (Nouveau monde) (net.minecraft.server.integrated.IntegratedServer@2edd88d1) [14:38:38] [Server thread/INFO] [FML]: Loading dimension -1 (Nouveau monde) (net.minecraft.server.integrated.IntegratedServer@2edd88d1) [14:38:38] [Server thread/INFO]: Preparing start region for level 0 [14:38:39] [Server thread/INFO]: Preparing spawn area: 31% [14:38:39] [Realms Notification Availability checker #1/INFO]: Could not authorize you against Realms server: Invalid session id [14:38:39] [Server thread/INFO]: Changing view distance to 12, from 10 [14:38:40] [Netty Local Client IO #0/INFO] [FML]: Server protocol version 2 [14:38:40] [Netty Server IO #1/INFO] [FML]: Client protocol version 2 [14:38:40] [Netty Server IO #1/INFO] [FML]: Client attempting to join with 4 mods : FML@8.0.99.99,Forge@11.15.1.1747,mcp@9.19,survivant@1.0.0 [14:38:40] [Netty Local Client IO #0/INFO] [FML]: [Netty Local Client IO #0] Client side modded connection established [14:38:40] [Server thread/INFO] [FML]: [Server thread] Server side modded connection established [14:38:41] [Server thread/INFO]: Player193[local:E:365416ba] logged in with entity id 118 at (-274.6609106403902, 70.0, 572.49508106187) [14:38:41] [Server thread/INFO]: Player193 a rejoint la partie [14:38:42] [pool-2-thread-1/WARN]: Couldn't look up profile properties for com.mojang.authlib.GameProfile@640e53f1[id=e6106110-0611-3c88-99d4-92770daab422,name=Player193,properties={},legacy=false] com.mojang.authlib.exceptions.AuthenticationException: The client has sent too many requests within a certain amount of time at com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService.makeRequest(YggdrasilAuthenticationService.java:65) ~[YggdrasilAuthenticationService.class:?] at com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService.fillGameProfile(YggdrasilMinecraftSessionService.java:175) [YggdrasilMinecraftSessionService.class:?] at com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService$1.load(YggdrasilMinecraftSessionService.java:59) [YggdrasilMinecraftSessionService$1.class:?] at com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService$1.load(YggdrasilMinecraftSessionService.java:56) [YggdrasilMinecraftSessionService$1.class:?] at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3524) [guava-17.0.jar:?] at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2317) [guava-17.0.jar:?] at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2280) [guava-17.0.jar:?] at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2195) [guava-17.0.jar:?] at com.google.common.cache.LocalCache.get(LocalCache.java:3934) [guava-17.0.jar:?] at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3938) [guava-17.0.jar:?] at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4821) [guava-17.0.jar:?] at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4827) [guava-17.0.jar:?] at com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService.fillProfileProperties(YggdrasilMinecraftSessionService.java:165) [YggdrasilMinecraftSessionService.class:?] at net.minecraft.client.Minecraft.func_181037_M(Minecraft.java:2915) [Minecraft.class:?] at net.minecraft.client.resources.SkinManager$3.run(SkinManager.java:130) [SkinManager$3.class:?] at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:1.8.0_121] at java.util.concurrent.FutureTask.run(Unknown Source) [?:1.8.0_121] at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_121] at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_121] at java.lang.Thread.run(Unknown Source) [?:1.8.0_121] [14:39:06] [Server thread/INFO]: Saving and pausing game… [14:39:06] [Server thread/INFO]: Saving chunks for level 'Nouveau monde'/Overworld [14:39:06] [Server thread/INFO]: Saving chunks for level 'Nouveau monde'/Nether [14:39:06] [Server thread/INFO]: Saving chunks for level 'Nouveau monde'/The End [14:39:32] [Server thread/INFO]: Saving and pausing game… [14:39:32] [Server thread/INFO]: Saving chunks for level 'Nouveau monde'/Overworld [14:39:32] [Server thread/INFO]: Saving chunks for level 'Nouveau monde'/Nether [14:39:32] [Server thread/INFO]: Saving chunks for level 'Nouveau monde'/The End [14:39:33] [Server thread/INFO]: Stopping server [14:39:33] [Server thread/INFO]: Saving players [14:39:33] [Server thread/INFO]: Saving worlds [14:39:33] [Server thread/INFO]: Saving chunks for level 'Nouveau monde'/Overworld [14:39:33] [Server thread/INFO]: Saving chunks for level 'Nouveau monde'/Nether [14:39:33] [Server thread/INFO]: Saving chunks for level 'Nouveau monde'/The End [14:39:33] [Server thread/INFO] [FML]: Unloading dimension 0 [14:39:33] [Server thread/INFO] [FML]: Unloading dimension -1 [14:39:33] [Server thread/INFO] [FML]: Unloading dimension 1 [14:39:34] [Server thread/INFO] [FML]: Applying holder lookups [14:39:34] [Server thread/INFO] [FML]: Holder lookups applied [14:39:34] [Client thread/INFO]: Stopping! [14:39:34] [Client thread/INFO]: SoundSystem shutting down… [14:39:34] [Realms Notification Availability checker #1/INFO]: Could not authorize you against Realms server: Invalid session id [14:39:34] [Client thread/WARN]: Author: Paul Lamb, www.paulscode.com Java HotSpot(TM) 64-Bit Server VM warning: Using incremental CMS is deprecated and will likely be removed in a future release
Merci d’avance.
-
Tu n’arrives pas à entrer dans le monde où il n’y avait juste aucun log pendant ta session de jeu ?
-
J’arrive à aller sur le monde, le seul souci c’est que lorsque je met la barre à 0, je ne prend pas de dégât alors que je devrais en prendre.
Merci par avance.
-
Étonnant comme chez moi ça fonctionne avec le même code …
Cliques sur workspace -> clean pour forcer eclipse à tout recompiler -
Je dois avoir un souci avec la capabilities ou même la fonction qui gère les ticks du joueurs. Maintenant, à chaque fois que je lance le jeu, visuellement, la barre de soif est au max mais quand je met un System.out.println(cap.getThirstVal()); la valeur est à 0.
Si je met des dégâts, même si la barre de soif est visuellement au max, je prend des dégâts.
Bizarre.Merci d’avance.
-
Envoies la classe de ta capability.
-
Voici :
La classe PacketThirstCapabilities :
package com.survivant.mod; import io.netty.buffer.ByteBuf; import net.minecraft.client.Minecraft; import net.minecraft.server.MinecraftServer; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class PacketThirstCapabilities implements IMessage { public static int thirstValue; public PacketThirstCapabilities(int thirstValue) { this.thirstValue = thirstValue; } public PacketThirstCapabilities() {} @Override public void fromBytes(ByteBuf buf) { this.thirstValue = buf.readInt(); } @Override public void toBytes(ByteBuf buf) { buf.writeInt(this.thirstValue); } public static class ServerHandler implements IMessageHandler <packetthirstcapabilities, imessage="">{ @Override public IMessage onMessage(PacketThirstCapabilities message, MessageContext ctx) { MinecraftServer.getServer().addScheduledTask(new ScheduledPacketTask(ctx.getServerHandler().playerEntity, message)); return null; } } @SideOnly(Side.CLIENT) public static class ClientHandler implements IMessageHandler <packetthirstcapabilities, imessage="">{ @Override public IMessage onMessage(PacketThirstCapabilities message, MessageContext ctx) { Minecraft.getMinecraft().addScheduledTask(new ScheduledPacketTask(null, message)); return null; } } }
La classe ScheduledPacketTask :
package com.survivant.mod; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class ScheduledPacketTask implements Runnable { private EntityPlayer player; private PacketThirstCapabilities message; public ScheduledPacketTask(EntityPlayer player, PacketThirstCapabilities message) { this.player = player; this.message = message; } @Override public void run() { EntityPlayer player = this.player == null ? getPlayer() : this.player; player.getCapability(ModSurvivant.T_CAP, null).setThirstVal(message.thirstValue); } @SideOnly(Side.CLIENT) private EntityPlayer getPlayer() { return Minecraft.getMinecraft().thePlayer; } }
La classe ThirstCapabilities :
package com.survivant.mod; import java.util.concurrent.Callable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.INBTSerializable; public class ThirstCapabilities implements ICapabilityProvider,INBTSerializable <nbttagcompound>{ public int thirstValue; private EntityPlayer player; @Override public boolean hasCapability(Capability capability, EnumFacing facing) { return ModSurvivant.T_CAP != null && capability == ModSurvivant.T_CAP; } @Override public <t>T getCapability(Capability <t>capability, EnumFacing facing) { return ModSurvivant.T_CAP != null && capability == ModSurvivant.T_CAP ? (T)this : null; } @Override public NBTTagCompound serializeNBT() { NBTTagCompound compound = new NBTTagCompound(); compound.setInteger("ThirstVal", this.getThirstVal()); return compound; } @Override public void deserializeNBT(NBTTagCompound compound) { this.setThirstVal(compound.getInteger("ThirstVal")); } public void setThirstVal(int thirstValue) { this.thirstValue = thirstValue; } public int getThirstVal() { return this.thirstValue; } public static class Storage implements Capability.IStorage <thirstcapabilities>{ @Override public NBTBase writeNBT(Capability <thirstcapabilities>capability, ThirstCapabilities instance, EnumFacing side) { return null; } @Override public void readNBT(Capability <thirstcapabilities>capability, ThirstCapabilities instance, EnumFacing side, NBTBase nbt) { } } public static class Factory implements Callable <thirstcapabilities>{ @Override public ThirstCapabilities call() throws Exception { return null; } } public static void register() { CapabilityManager.INSTANCE.register(ThirstCapabilities.class, new ThirstCapabilities.Storage(), new ThirstCapabilities.Factory()); } public ThirstCapabilities(EntityPlayer player) { this.thirstValue = 86; this.player = player; } public void sync() { PacketThirstCapabilities packet = new PacketThirstCapabilities(this.getThirstVal()); if(!this.player.worldObj.isRemote) { EntityPlayerMP playerMP = (EntityPlayerMP)player; ModSurvivant.network.sendTo(packet, playerMP); } else { ModSurvivant.network.sendToServer(packet); } } }
Merci par avance.</thirstcapabilities></thirstcapabilities></thirstcapabilities></thirstcapabilities></t></t></nbttagcompound></packetthirstcapabilities,></packetthirstcapabilities,>
-
thirstValue ne devrait pas être static dans la classe PacketThirstCapabilities.
Je ne vois pas d’autres problèmes sinon. -
Changes
@Override public NBTTagCompound serializeNBT() { NBTTagCompound compound = new NBTTagCompound(); compound.setInteger("ThirstVal", this.getThirstVal()); return compound; } @Override public void deserializeNBT(NBTTagCompound compound) { this.setThirstVal(compound.getInteger("ThirstVal")); }
Par
@Override public NBTTagCompound serializeNBT() { return Storage.writeNBT(ModSurvivant.T_CAP, this, null);//Le this est peut-être faux } @Override public void deserializeNBT(NBTTagCompound compound) { Storage.readNBT(ModSurvivant.T_CAP, this, null, compound);//Pareil }
Et
@Override public NBTBase writeNBT(Capability <thirstcapabilities>capability, ThirstCapabilities instance, EnumFacing side) { return null; } @Override public void readNBT(Capability <thirstcapabilities>capability, ThirstCapabilities instance, EnumFacing side, NBTBase nbt) { }
Par
@Override public NBTBase writeNBT(Capability <thirstcapabilities>capability, ThirstCapabilities instance, EnumFacing side) { return new NBTTagInt(instance.getThirstVal()); } @Override public void readNBT(Capability <thirstcapabilities>capability, ThirstCapabilities instance, EnumFacing side, NBTBase nbt) { if(nbt instanceof NBTTagInt) instance.setThirstVal(((NBTTagInt) nbt).getInt()); }
Aussi, le fait que tu mettes tout dans une class n’aide pas.
Je te conseil de tout mettre en 5 classes :
-IThirst → Interface qui comprend les méthodes getThirstVal et setThirstVal,
-**ThirstCap **→ Class qui implémente **IThirst **et qui contient la variable thirstValue en field,
-**ThirstProvider **→ Class qui implémente ICapabilitySerializable<nbtbase>, et qui contient notamment l’instance de Capability<ithirst>,
-**ThirstStorage **→ Class qui implémente IStorage<ithirst>. C’est ici où tu dois écrire et lire les NBT,
-**CapabilityHandler **→ Class qui contient l’event AttachCapabilitiesEvent. <type>(ici Entity) afin d’attacher le capability au joueur.
Ça permettrait d’avoir un code plus lisible.Aussi, si le joueur change de dimension, il va perdre toutes les valeurs de son capability. Pour cela, avec l’event PlayerEvent.Clone, vérifie que isWasDeath() est *false *et ainsi mettre les valeurs du capability de l’ancien joueur sur le nouveau.
Voici un tutorial en anglais qui explique très bien comment faire tout cela : http://www.planetminecraft.com/blog/forge-tutorial-capability-system/.</type></ithirst></ithirst></nbtbase></thirstcapabilities></thirstcapabilities></thirstcapabilities></thirstcapabilities>
-
J’ai suivi le tuto sans sucés puisque le jeu crash à la génération du monde. Aussi, voici si join le dossier avec les classes concernées.
Les capability et moi décidément ça fait 2, il n’y a pas un moyen plus simple d’enregistrer une valeur pour un joueur ?
Merci par avance.
-
Changes
@Override public <t>T getCapability(Capability <t>capability, EnumFacing facing) { return capability == THIRST_CAP ? (T)this.instance : null; }
Par
@Override public <t>T getCapability(Capability <t>capability, EnumFacing facing) { return capability == THIRST_CAP ? THIRST_CAP.<t>cast(this.instance) : null; }
Si tu crash encore, envoies le crash report.</t></t></t></t></t>
-
J’ai une erreur sur cast.