Jump to content

Recommended Posts

Posted

Hi!

 

I am just writing the last part of a minigame-server project and need a way to access the Scoreboard.

I know that I can use world.getScoreboard() to get the scoreboard, but now i am a little bit stuck.

 

I tried to use

.func_96516_a("adsasdasd");

to add a title to my scoreboard, but when i tested it nothing happened.

(Player joined after scoreboard was created)

 

So how would I set the title correctly? Or do I have to send my scoreboard to the player/add my player to the scoreboard?

 

Jacky

Here could be your advertisement!

Posted

There is some method called "addScoreObjective", you might want that.

 

In case it is not deobfed in 1.8 (I found it on 1.7.10),

  it has two parameters : String, IScoreObjectiveCriteria, and it returns ScoreObjective.

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

Posted

The problem is that the player doesn't even display stuff such as the teams color.

 

To create the teams I use:

	for(int i=0; i<teamNumber;i++){
		//scoreboard.createTeam(i+"");
		ScorePlayerTeam team = new ScorePlayerTeam(scoreboard,i+"");
		team.setTeamName(EnumTeam.values()[i].toString());
		team.func_178774_a(EnumTeam.values()[i].getChatColor());
		team.setNamePrefix("TEST");
		scoreboard.sendTeamUpdate(team);
	}

once the dim is generated.

 

And then I want to use:

		    		player.worldObj.getScoreboard().addPlayerToTeam(player.getName(), (i+""));

 

To add my player to the team. Problem is: nothing happens. No name suffix, no color, ...

 

According to a bukkit tut here I have to set the players scoreboard somehow, but I have no idea how I should do this.

 

I found

	player.setScore(int x);

 

But this requires an int for the data watcher, and I don't know how I can get the scoreboards id.

 

 

I will try to find some more information in the scoreboard command, but it would be awesome if someone could help me here.

Here could be your advertisement!

Posted

Where do you add your ScoreObjective to the ScoreBoard? Relevant code would be needed.

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

Posted

In my main class:

 

 

...
    @EventHandler
    public void preInit(FMLPreInitializationEvent event)
    {
    	if(!baseFolder.exists()){
    		baseFolder.mkdir();
    	}
    	
	DimensionManager.registerProviderType(providerTypeSkyBattle, WorldProviderSkyBattle.class, true);

    	RegisterDimensions.register(true);

    	
    }

...

    @EventHandler
    public void serverStarted(FMLServerStartedEvent event){
    	RegisterDimensions.register(false);
    }

 

 

 

RegisterDimensionClass:

 

 

 

public class RegisterDimensions {

public static void register(boolean preInit){

	//SKYBATTLE
	for(int i=BlackGeckoServer.firstSkyBattleServer;i<25;i++){
		if(preInit){
			DimensionManager.registerDimension(i, BlackGeckoServer.providerTypeSkyBattle);
		} else {
			BlackGeckoServer.gameServer.put(i, new SkyBattle(i));
		}
	}





}

}

 

 

 

my Skybattle class:

 

 

public class SkyBattle extends GameMode{

public int teamNumber;

public int playerPerTeam;

public List[] teams ={new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>()};



public SkyBattle(int i) {
	this(i,1, 1,1);
}


public SkyBattle(int dim, int map, int teams, int playersPerTeam) {

	this.dim=dim;
	this.map=map;
	this.teamNumber=teams;
	this.playerPerTeam=playersPerTeam;
	this.state=EnumGameState.RESTARTING;

	this.resetWorld(EnumGameMode.SKY_BATTLE, this.map, this.dim);

	this.createScoreboard();



}

public void createScoreboard(){
	Scoreboard scoreboard = MinecraftServer.getServer().worldServerForDimension(this.dim).getScoreboard();

	for(int i=0; i<teamNumber;i++){
		//scoreboard.createTeam(i+"");
		ScorePlayerTeam team = new ScorePlayerTeam(scoreboard,i+"");
		team.setTeamName(EnumTeam.values()[i].toString());
		team.func_178774_a(EnumTeam.values()[i].getChatColor());
		team.setNamePrefix("TEST");
		scoreboard.sendTeamUpdate(team);
	}
}


@Override
public void joinPlayer(EntityPlayer player){
	boolean alreadyOnline=false;


	player.setCustomNameTag("asdasdasd");


	for(EntityPlayer player1 : this.players){
		if(player1 == player)
			alreadyOnline=true;
	}
	if(!alreadyOnline){
		this.players.add(player);
	}

	if(this.players.size()>=this.playerPerTeam*this.teamNumber){
		for (EntityPlayer player1 : this.players) {
		    player1.addChatComponentMessage(new ChatComponentText("The game has started."));
		    this.countdown();
		}
	}
}

@Override
public void disconnectPlayer(EntityPlayer player){
	players.remove(player);
    for(int i=0;i<this.teams.length;i++){
    	if(this.teams[i].contains(player))
    		this.teams[i].remove(player);
    }
   
}

public void joinTeam(EntityPlayer player, EnumTeam team){
	if(team.ordinal()<this.teamNumber){

			if(teams[team.ordinal()].contains(player)){

				teams[team.ordinal()].remove(player);

				player.addChatComponentMessage(new ChatComponentText("You left Team " + team.toString()));
			} else {
					if(teams[team.ordinal()].size()<this.playerPerTeam){

						for(int i=0; i<teams.length;i++){
							if(teams[i].contains(player)){
								teams[i].remove(player);
							}
						}

						teams[team.ordinal()].add(player);	


						player.addChatComponentMessage(new ChatComponentText(team.getChatColor() + "You joined team " + team.toString() + "."));
						player.setCustomNameTag(team.getChatColor()+player.getName());

					} else {
						player.addChatComponentMessage(new ChatComponentText("This team is already full."));
					}


				}

	} else {
		player.addChatComponentMessage(new ChatComponentText(EnumChatFormatting.DARK_RED+"The team you were about to join does not exist."));
	}
}

public void autojoinTeam(){
	for (EntityPlayer player : this.players) {
	    boolean isInTeam=false;
	    
	    for(int i=0;i<this.teams.length;i++){
	    	if(this.teams[i].contains(player))
	    		isInTeam=true;
	    }
	    
	    if(!isInTeam){
		    for(int i=0;i<this.teams.length;i++){
		    	if(this.teams[i].size()<this.playerPerTeam){
		    		this.teams[i].add(player);
		    		
		    		
		    		
					player.addChatComponentMessage(new ChatComponentText(EnumTeam.values()[i].getChatColor() + "You joined team " + EnumTeam.values()[i].toString() + "."));
					player.setCustomNameTag(EnumTeam.values()[i].getChatColor().toString() +player.getName());


					Scoreboard scoreboard = MinecraftServer.getServer().worldServerForDimension(this.dim).getScoreboard();


					scoreboard.addPlayerToTeam(player.getName(), (i+""));
					scoreboard.addPlayerToTeam(player.getName(), EnumTeam.values()[i].toString());
		    		
		    		//System.out.println(player.worldObj.getScoreboard().getTeam(i+"").);
		    		
		    		break;
		    	}
		    }
	    }



	}
}

@Override
public void start(){
	this.autojoinTeam();

	for(EntityPlayer player : players){
		DisplayTitle.sendTitle(player, S45PacketTitle.Type.TITLE, new ChatComponentText("SKY BATTLE")); //MOVE TO GAME MODE CLASS IN NEW FUNCTION!!!!
	}

	this.messageToAllPlayers(new ChatComponentText(EnumChatFormatting.AQUA +"The game has started!"));

	this.messageToAllPlayers(new ChatComponentText(EnumChatFormatting.WHITE +"As long as your beacon is not destroyed you can respawn at you base."));
	this.messageToAllPlayers(new ChatComponentText(EnumChatFormatting.WHITE +"Try to destroy the enemies beacon to win."));


}


}

 

 

 

 

Btw, for everyone who is creating something similar, I wrote a class to display a title. Its not perfect but it works:

 

 

 

public class DisplayTitle {

public static boolean sendTitle(EntityPlayer player, S45PacketTitle.Type type){
	if (type != S45PacketTitle.Type.CLEAR && type != S45PacketTitle.Type.RESET){
		return false;
	} else {
		return sendTitle(player, type, null);
	}
}


public static boolean sendTitle(EntityPlayer player, S45PacketTitle.Type type, ChatComponentText message){
	return sendTitle(player, type, message, 1, 5, 1);
}


public static boolean sendTitle(EntityPlayer player, S45PacketTitle.Type type, ChatComponentText message, int fadeIn, int stay, int fadeOut){
	EntityPlayerMP entityplayermp =(EntityPlayerMP) player;

	ICommandSender commandSender = MinecraftServer.getServer();


	if (type != S45PacketTitle.Type.CLEAR && type != S45PacketTitle.Type.RESET){

		S45PacketTitle s45packettitle1;
		try {
			s45packettitle1 = new S45PacketTitle(type, ChatComponentProcessor.func_179985_a(commandSender, message, player));
		    entityplayermp.playerNetServerHandler.sendPacket(s45packettitle1);
		    return true;
		} catch (CommandException e) {
			// TODO Auto-generated catch block
			return false;
		}
	    
	} else {
        S45PacketTitle s45packettitle = new S45PacketTitle(type, (IChatComponent)null);
        entityplayermp.playerNetServerHandler.sendPacket(s45packettitle);	
        return true;
}
}
}

 

 

Here could be your advertisement!

Posted

You should get team from Scoreboard class, via Scoreboard#createTeam(String).

  (In case it wasn't deobfuscated in 1.8, the method returns ScorePlayerTeam)

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

Posted

oh, looks like my player actually joined my team, but the nametag color was never changed....

I am using

team.func_178774_a(EnumChatFormatting.RED);

But nothing really changes. Any ideas why?

 

Here is my latest SkyBattle class.

 

 

package com.blackgeckogames.server.mod.minigames.skybattle;

import java.util.ArrayList;
import java.util.List;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.play.server.S45PacketTitle;
import net.minecraft.scoreboard.ScorePlayerTeam;
import net.minecraft.scoreboard.Scoreboard;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;

import com.blackgeckogames.server.mod.minigames.GameMode;
import com.blackgeckogames.server.mod.utilities.DisplayTitle;

public class SkyBattle extends GameMode{

public int teamNumber;

public int playerPerTeam;

public List[] teams ={new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>(),new ArrayList<EntityPlayer>()};



public SkyBattle(int i) {
	this(i,1, 1,1);
}


public SkyBattle(int dim, int map, int teams, int playersPerTeam) {

	this.dim=dim;
	this.map=map;
	this.teamNumber=teams;
	this.playerPerTeam=playersPerTeam;
	this.state=EnumGameState.RESTARTING;

	this.resetWorld(EnumGameMode.SKY_BATTLE, this.map, this.dim);

	this.createScoreboard();



}

public void createScoreboard(){
	Scoreboard scoreboard = MinecraftServer.getServer().worldServerForDimension(this.dim).getScoreboard();

	for(int i=0; i<teamNumber;i++){
		if(scoreboard.getTeam(EnumTeam.values()[i].toString())==null){
			scoreboard.createTeam(EnumTeam.values()[i].toString());
		}
		//ScorePlayerTeam team = new ScorePlayerTeam(scoreboard,i+"");
		ScorePlayerTeam team = scoreboard.getTeam(EnumTeam.values()[i].toString());
		team.setTeamName(EnumTeam.values()[i].toString());
		team.func_178774_a(EnumChatFormatting.RED);
		team.setNamePrefix("TEST");

		scoreboard.sendTeamUpdate(team);
	}
}


@Override
public void joinPlayer(EntityPlayer player){
	boolean alreadyOnline=false;


	player.setCustomNameTag("asdasdasd");


	for(EntityPlayer player1 : this.players){
		if(player1 == player)
			alreadyOnline=true;
	}
	if(!alreadyOnline){
		this.players.add(player);
	}

	if(this.players.size()>=this.playerPerTeam*this.teamNumber){
		for (EntityPlayer player1 : this.players) {
		    player1.addChatComponentMessage(new ChatComponentText("The game has started."));
		    this.countdown();
		}
	}
}

@Override
public void disconnectPlayer(EntityPlayer player){
	players.remove(player);
    for(int i=0;i<this.teams.length;i++){
    	if(this.teams[i].contains(player))
    		this.teams[i].remove(player);
    }
   
}

public void joinTeam(EntityPlayer player, EnumTeam team){
	if(team.ordinal()<this.teamNumber){

			if(teams[team.ordinal()].contains(player)){

				teams[team.ordinal()].remove(player);

				player.addChatComponentMessage(new ChatComponentText("You left Team " + team.toString()));
			} else {
					if(teams[team.ordinal()].size()<this.playerPerTeam){

						for(int i=0; i<teams.length;i++){
							if(teams[i].contains(player)){
								teams[i].remove(player);
							}
						}

						teams[team.ordinal()].add(player);	


						player.addChatComponentMessage(new ChatComponentText(team.getChatColor() + "You joined team " + team.toString() + "."));
						player.setCustomNameTag(team.getChatColor()+player.getName());

					} else {
						player.addChatComponentMessage(new ChatComponentText("This team is already full."));
					}


				}

	} else {
		player.addChatComponentMessage(new ChatComponentText(EnumChatFormatting.DARK_RED+"The team you were about to join does not exist."));
	}
}

public void autojoinTeam(){
	for (EntityPlayer player : this.players) {
	    boolean isInTeam=false;
	    
	    for(int i=0;i<this.teams.length;i++){
	    	if(this.teams[i].contains(player))
	    		isInTeam=true;
	    }
	    
	    if(!isInTeam){
		    for(int i=0;i<this.teams.length;i++){
		    	if(this.teams[i].size()<this.playerPerTeam){
		    		this.teams[i].add(player);
		    		
		    		
		    		
					player.addChatComponentMessage(new ChatComponentText(EnumTeam.values()[i].getChatColor() + "You joined team " + EnumTeam.values()[i].toString() + "."));
					player.setCustomNameTag(EnumTeam.values()[i].getChatColor().toString() +player.getName());


					Scoreboard scoreboard = MinecraftServer.getServer().worldServerForDimension(this.dim).getScoreboard();


					//scoreboard.addPlayerToTeam(player.getName(), (i+""));
					scoreboard.addPlayerToTeam(player.getName(), EnumTeam.values()[i].toString());
		    		
		    		//System.out.println(player.worldObj.getScoreboard().getTeam(i+"").);
		    		
		    		break;
		    	}
		    }
	    }



	}
}

@Override
public void start(){
	this.autojoinTeam();

	for(EntityPlayer player : players){
		DisplayTitle.sendTitle(player, S45PacketTitle.Type.TITLE, new ChatComponentText("SKY BATTLE"));
	}

	this.messageToAllPlayers(new ChatComponentText(EnumChatFormatting.AQUA +"The game has started!"));

	this.messageToAllPlayers(new ChatComponentText(EnumChatFormatting.WHITE +"As long as your beacon is not destroyed you can respawn at you base."));
	this.messageToAllPlayers(new ChatComponentText(EnumChatFormatting.WHITE +"Try to destroy the enemies beacon."));


}


}

 

 

Here could be your advertisement!

Posted

Ok, fixed it by using:

 

            team.func_178774_a(EnumTeam.values()[i].getChatColor());
            team.setNamePrefix(EnumTeam.values()[i].getChatColor().toString());
            team.setNameSuffix(EnumChatFormatting.RESET.toString());			

 

Thats great. However, all my players are automatically added to the scoreboard. Not so great. Also it seems like the same scoreboard is used in all dimensions. How can i avoid this?

Here could be your advertisement!

Posted

1. Scoreboard instance should be per world, so it is strange..

2. Where the joinPlayer method get called?

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

Posted

Ok, not sure why, but after I added some empty lines the player isn't in the first team by default.

However, he still keeps his in team in another dim...

 

 

@SubscribeEvent
public void onEntityJoinWorldEvent(EntityJoinWorldEvent event){
	if(event.entity instanceof EntityPlayer){
                
                 ...

		if(BlackGeckoServer.gameServer.containsKey(event.world.provider.getDimensionId())){
			System.out.println("JOINED !!!!!!");
			BlackGeckoServer.gameServer.get(event.world.provider.getDimensionId()).joinPlayer(player);
		}	
	}
}

Here could be your advertisement!

Posted

Oh. I just found out that Scoreboard is saved in mapStorage, which is for per map, not per world.

  Then, you should have to add/remove player in the Team when the player joins/leaves the world.

I. Stellarium for Minecraft: Configurable Universe for Minecraft! (WIP)

II. Stellar Sky, Better Star Rendering&Sky Utility mod, had separated from Stellarium.

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

    • It is 1.12.2 - I have no idea if there is a 1.12 pack
    • 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() ); } }  
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

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