Jump to content

Recommended Posts

Posted

Hey folks,

 

I've got a problem in my project that I can't fix:

 

package utils;

import java.io.File;
import java.util.ArrayList;

import handler.InputHandler;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumParticleTypes;
import net.minecraftforge.common.config.Configuration;

public class Marker {

private static File route = null;

public static void setRoute ( File file ) { route = file; }

/**
 * This method gets used when the player starts riding
 * with this method, I can markup the blocks of the loaded route by sending
 * particle packages to the player
 * @param bool The boolean witch I use for my loop
 */
public static void markupWay ( boolean bool ) {

	if ( route != null ) { route = InputHandler.route; }

	Configuration config = new Configuration ( route );

	if ( bool ) {

		/* Goes through all block objects in the list... */
		for ( Block block : getBlocksNearby( Minecraft.getMinecraft().thePlayer , 10 ) ) {

			for ( int i = 0; i < RouteReader.getMarkerPoints( config ); i++ ) {

				/* ... and if the x-coord is equal to an value in the config... */
				if ( config.get( "posX" , i + ":" , 0 ).getInt() == ( int ) block.getBlockBoundsMaxX() ) {

					/* ... and if the y-coord is equal to an value in the config... */
					if ( config.get( "posY" , i + ":" , 0 ).getInt() == ( int ) block.getBlockBoundsMaxY() ) {

						/* ... and if the z-coord is equal to an value in the config... */
						if ( config.get( "posZ" , i + ":" , 0 ).getInt() == ( int ) block.getBlockBoundsMaxZ() ) {

							/* Then I will send particles at the blocks position */
							Minecraft.getMinecraft().thePlayer.worldObj.spawnParticle( EnumParticleTypes.REDSTONE ,
									                       ( ( block.getBlockBoundsMaxX() + block.getBlockBoundsMinX() ) / 2 ) ,
									                       ( ( block.getBlockBoundsMaxY() + block.getBlockBoundsMinY() ) / 2 ) ,
									                       ( ( block.getBlockBoundsMaxZ() + block.getBlockBoundsMinZ() ) / 2 ) ,
									                       0.3 , 0.3 , 0.3 );

						}

					}

				}

			}

		}
		//TODO Test if block is in list
		//send particle
		markupWay( bool );

	}

}

public static ArrayList < Block > getBlocksNearby ( Entity player , int radius ) {

	ArrayList < Block > list = new ArrayList < Block > ();

	for ( int x = ( int ) player.posX - radius; x <= ( int ) player.posX + radius; x++ ) {

		for ( int y = ( int ) player.posY - radius; y <= ( int ) player.posY + radius; y++ ) {

			for ( int z = ( int ) player.posZ - radius; z <= ( int ) player.posZ + radius; z++ ) {

				if ( !list.contains( player.worldObj.getBlockState( new BlockPos ( x , y , z ) ).getBlock() ) ) {

					list.add( player.worldObj.getBlockState( new BlockPos ( x , y , z ) ).getBlock() );

				}

			}

		}

	}

	return list;

}

}

 

The player can choose a route and as soon as he starts riding by pressing a button, I want particles to spawn above the blocks, which are registered in the routes file. When I run the code, the game stops working and nothing happens and no crash-log will be created.

 

Thanks in advance  :-\

*Hug*

Posted

I think you have an issue with infinite loop.

Debug it with breakpoint.

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

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

Posted

Nothing happens.

There is nothing in my console and "breakpoint" doesn't give me any information...

 

As I said: The game just crashes without any output into the console or something like that.

 

As long as the player is riding, the particles have to spawn above the blocks. As you can see in the code, the method is called anew while the boolean is true and the boolean is true as long the player is riding.

*Hug*

Posted

Nothing happens.

There is nothing in my console and "breakpoint" doesn't give me any information...

 

As I said: The game just crashes without any output into the console or something like that.

 

As long as the player is riding, the particles have to spawn above the blocks. As you can see in the code, the method is called anew while the boolean is true and the boolean is true as long the player is riding.

The game crashes? Then please provide the log.

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

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

Posted

"crashes" is the wrong word. When I press the button, a boolean gets set to true and then I call the method which will call itself as long as the boolean is true. But when this happens, the window doesn't react and gets whitish.

 

And thats the problem: I don't get ANY output and so I cannot figure out the problem

 

EDIT: I found out that the array only holds 7 elements and these elements are just blocktypes. Thats a new problem D:

        Is there a way to get blocks in a specified radius? I wrote several methods but no method

        really worked.  :'(

*Hug*

Posted

Then it is not a crash.

 

It is indeed - infinite loop.

 

You pass true to method that infinitely calls itself. The boolean won't change, why would it?

 

Also note - Blocks can have metadatas and other shit - you sure you want List<Block>?

1.7.10 is no longer supported by forge, you are on your own.

Posted

1. The boolean will change. When the boolean is false and the player presses the specified button for auto-riding, the boolean will change to true. When it's true it will change to false.

 

But if I pass true to the method the game instantly freezes and nothing gets outputted and I don't have the chance to change the passed boolean because it freezes.

 

2. I just want to get the blocks in the radius and then test if their coords are registered in the route-file.

*Hug*

Posted

Unless you are doing something behind the scenes - this is the code I see:

 

public static void markupWay ( boolean bool ) {

	if ( route != null ) { route = InputHandler.route; }

	Configuration config = new Configuration ( route );

	if ( bool ) {

		/* Goes through all block objects in the list... */
		for ( Block block : getBlocksNearby( Minecraft.getMinecraft().thePlayer , 10 ) ) {

			for ( int i = 0; i < RouteReader.getMarkerPoints( config ); i++ ) {

				/* ... and if the x-coord is equal to an value in the config... */
				if ( config.get( "posX" , i + ":" , 0 ).getInt() == ( int ) block.getBlockBoundsMaxX() ) {

					/* ... and if the y-coord is equal to an value in the config... */
					if ( config.get( "posY" , i + ":" , 0 ).getInt() == ( int ) block.getBlockBoundsMaxY() ) {

						/* ... and if the z-coord is equal to an value in the config... */
						if ( config.get( "posZ" , i + ":" , 0 ).getInt() == ( int ) block.getBlockBoundsMaxZ() ) {

							/* Then I will send particles at the blocks position */
							Minecraft.getMinecraft().thePlayer.worldObj.spawnParticle( EnumParticleTypes.REDSTONE ,
									                       ( ( block.getBlockBoundsMaxX() + block.getBlockBoundsMinX() ) / 2 ) ,
									                       ( ( block.getBlockBoundsMaxY() + block.getBlockBoundsMinY() ) / 2 ) ,
									                       ( ( block.getBlockBoundsMaxZ() + block.getBlockBoundsMinZ() ) / 2 ) ,
									                       0.3 , 0.3 , 0.3 );

						}

					}

				}

			}

		}
		//TODO Test if block is in list
		//send particle
		markupWay( bool );

	}

}

 

Now let's cut out all loops that do nothing regarding actualy result:

 

public static void markupWay ( boolean bool ) {
	if ( route != null ) { route = InputHandler.route; }

	Configuration config = new Configuration ( route );

	if ( bool ) {
		//TODO Test if block is in list
		//send particle
		markupWay( bool );
	}
}

 

If you EVER call "markupWay(true)" - It WILL roll INFINITELY!

That boolean is method-local, it cannot change out of methods scope - whatever you do.

 

Aside from that - EVEN if method would be called client side and the boolean would be global - just by calling method (when global boolean is true) would kill process (throttle client so hard that any key-input would not be able to pass to client thread).

 

You need either ClientTickEvent to run process for you (20ticks = 20 Hz) or you need to make new background thread which would introduce you to multithreading (which I don't think you would be able to code).

1.7.10 is no longer supported by forge, you are on your own.

Posted

I will do it with the ClientTickEvent.

 

But there's another problem:

The method "getBlocksNearby" is intended to get all blocks in the specified radius. But the method just returns the amount of different blocktypes...

*Hug*

Posted

I strongly assume that this is client only stuff - right? (because if not, you will be pretty much fked :) )

 

Issue 1:

 

1. Have a global boolean;

2. @SubscribeEvent to ClientTickEvent

* Check against event.phase (pick one)

* if (globalBoolean) markupWay(); (note that it will not call itself)

3. @SubscribeEvent to KeyInputEvent (or other, just look into client event package)

* Use it to change globalBoolean.

 

Result: You will be calling method per tick until you change state.

 

Issue 2:

 

What is the actualy purpose of method? Do you want to have List of Block types that are around you or list of actual data about blocks around?

 

Block is a singleton that is literally a description of what some position (block) means in world (position in world say "I am this block").

BlockState is a thing that tells you what this BlockPos currently is (its state, like rotation or other stuff).

 

If you would do check against Block using contains() - you would end up with list { COBBLE, STONE, DIRT, WATER, .... other }. Size of list will be number of different block types (singletons).

If you want to have actual states you need list of IBlockState and add them by state (size of list will be x*y*z).

 

Generally you don't really want to have IBlockState list since you should be having List<BlockPos> and then get BlockState directly from world.

 

Jesus christ, something is wrong with me, I make sooo many miss-typos lately (edited a lot), it is getting scary.

1.7.10 is no longer supported by forge, you are on your own.

Posted
1. Have a global boolean;

2. @SubscribeEvent to ClientTickEvent

* Check against event.phase (pick one)

* if (globalBoolean) markupWay(); (note that it will not call itself)

3. @SubscribeEvent to KeyInputEvent (or other, just look into client event package)

* Use it to change globalBoolean.

Already done before you wrote it  ;) The boolean was even global before

 

What is the actualy purpose of method?

I want the method to put ALL blocks within a radius of 10 blocks array. Then I want to check if the coords of the block-object I am currently testing are the same as a coordinate-bundle in the file. So basicly I want to put every single block with its data into this array and not just the type.

*Hug*

Posted

Okay - IBlockState represents Data held by World at some BlockPos.

 

IBlockState gives you access to:

* Block (type) - #getBlock() (saved as ID in world)

* Metadata = 16 bits = "state". (metadata is saved in world itself).

* "Actual state" - which is extended "state" that can represent not only those 16 bits of saved data, but also be modified by other factors - like TileEntity or neighbor blocks.

 

As said - there are very few cases in which you will need List<IBlockState> since IBlockState is NOT BOUND to BlockPos.

 

Said that, best approach would be:

for (x)
    for (y)
        for (z)
            IBlockState state = player.worldObj.getBlockState(new BlockPos( x , y , z ));
            // now you have access to x, y, z, Block (type) and metadata.
            // Do rest of your "markupWay" method's code here.

 

Also note - idk how your config looks, so maybe there would be better way of doing it.

1.7.10 is no longer supported by forge, you are on your own.

Posted

Now I done everything you said.

 

When I don't filter the states...

public static ArrayList < IBlockState > getBlocksNearby ( Entity player , int radius ) {

	ArrayList < IBlockState > stateList = new ArrayList < IBlockState > ();

	for( int x = ( int ) Math.min( player.posX - radius , player.posX + radius ); x <= Math.max( player.posX - radius , player.posY + radius ); x++ ) {

		for( int y = ( int ) Math.min( player.posY - radius , player.posY + radius ); y <= Math.max( player.posY - radius , player.posY + radius ); y++ ) {

			for( int z = ( int ) Math.min( player.posZ - radius , player.posZ + radius ); z <= Math.max( player.posZ - radius , player.posZ + radius ); z++ ) {

				IBlockState state = player.worldObj.getBlockState( new BlockPos ( x , y , z ) );
				stateList.add( state );

			}

		}

	}

	return stateList;

}

... it will output "148617", I guess that's the amount of different states for the blocks within a radius of 10. In the same moment the game freezes and I have to close the window BUT the programm still outputs my sysout's.

 

Now I'm gone further but the game still freezes  :'(

 

Code:

	private static File route = null;
Configuration config = null;
private static boolean markingUp = false;

public static void setRoute ( File file ) { route = file; }

/**
 * This method gets used when the player starts riding
 * with this method, I can markup the blocks of the loaded route by sending
 * particle packages to the player
 * @param bool The boolean which I use for my loop
 */
public static boolean markupWay ( boolean bool ) {

	markingUp = bool;
	return bool;

}

public static ArrayList < IBlockState > getBlocksNearby ( Entity player , int radius ) {

	ArrayList < IBlockState > stateList = new ArrayList < IBlockState > ();

	for( int x = ( int ) Math.min( player.posX - radius , player.posX + radius ); x <= Math.max( player.posX - radius , player.posY + radius ); x++ ) {

		for( int y = ( int ) Math.min( player.posY - radius , player.posY + radius ); y <= Math.max( player.posY - radius , player.posY + radius ); y++ ) {

			for( int z = ( int ) Math.min( player.posZ - radius , player.posZ + radius ); z <= Math.max( player.posZ - radius , player.posZ + radius ); z++ ) {

				IBlockState state = player.worldObj.getBlockState( new BlockPos ( x , y , z ) );
				if ( stateList.contains( state ) ) {
					stateList.add( state );
				}

			}

		}

	}

	return stateList;

}

@SubscribeEvent
public void onClientTick ( TickEvent.ClientTickEvent e ) {

	if ( e.phase == Phase.END ) {

		System.out.println( "test" );

		if ( markingUp ) {

			System.out.println( "debug inner" );

			if ( route == null ) { route = InputHandler.route; }
			if ( config == null ) { config = new Configuration ( route ); }

			ArrayList < IBlockState > stateList = getBlocksNearby( Minecraft.getMinecraft().thePlayer , 10 );

			System.out.println( stateList.size() );
			for ( IBlockState state : stateList ) {

				for ( int i = 0; i < RouteReader.getMarkerPoints( config ); i++ ) {

					if ( config.get( "posX" , i + ":" , 0 ).getInt() == ( int ) state.getBlock().getBlockBoundsMaxX() ) {

						if ( config.get( "posY" , i + ":" , 0 ).getInt() == ( int ) state.getBlock().getBlockBoundsMaxY() ) {

							if ( config.get( "posZ" , i + ":" , 0 ).getInt() == ( int ) state.getBlock().getBlockBoundsMaxZ() ) {

								Minecraft.getMinecraft().thePlayer.worldObj.spawnParticle( EnumParticleTypes.REDSTONE ,
					                       ( ( state.getBlock().getBlockBoundsMaxX() + state.getBlock().getBlockBoundsMinX() ) / 2 ) ,
					                       ( ( state.getBlock().getBlockBoundsMaxY() + state.getBlock().getBlockBoundsMinY() ) / 2 ) ,
					                       ( ( state.getBlock().getBlockBoundsMaxZ() + state.getBlock().getBlockBoundsMinZ() ) / 2 ) ,
					                       0.3 , 0.3 , 0.3 );

							}

						}

					}

				}

			}

		}

	}

}

 

Anyway... Thank you for the help so far ;)

 

*Hug*

Posted

I am kinda lost with what is actually your goal. You have some "marker points" in configs, but what's up with "#getBlock().getBlockBoundsMaxX()"?

What is your actual goal - in words?

1.7.10 is no longer supported by forge, you are on your own.

Posted
I want the method to put ALL blocks within a radius of 10 blocks array. Then I want to check if the coords of the block-object I am currently testing are the same as a coordinate-bundle in the file.

For this I used the MaxX, MaxY and MaxZ... :-X

They're just used to compare the coords-bundle in the config, like you said, and the coords of the block. If there is match, I will spawn particles above it...

*Hug*

Posted

I'm befuddled by a couple things. First:

 

if ( stateList.contains( state ) ) {
	stateList.add( state );
}

If the state is already in the list, why would you add it again? And if the list starts empty, will this test ever allow a state to be added?

 

Second: Why is there a posY in your loop code for x?

 

Third: Why are you getting so many blocks in a solid volume? Look through World to see how vanilla Minecraft scans for things. You may find a method already out there that will suffice. In any case, there must be a more efficient algorithm (find the next path block at radius one, then find one adjacent to that etc).

 

Fourth: What is going to happen if your player is ever near y=255 or y=1? Or in a superflat world with even tighter constraint on y?

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

Posted
I'm befuddled by a couple things. First:

 

Code: [select]

if ( stateList.contains( state ) ) {

stateList.add( state );

}

If the state is already in the list, why would you add it again? And if the list starts empty, will this test ever allow a state to be added?

That's a left-over from old code I made. Sorry about that ;)

 

Second: Why is there a posY in your loop code for x?

Mistake xP

 

Third: Why are you getting so many blocks in a solid volume? Look through World to see how vanilla Minecraft scans for things. You may find a method already out there that will suffice. In any case, there must be a more efficient algorithm (find the next path block at radius one, then find one adjacent to that etc).
May be. I will take a look into the code

 

Fourth: What is going to happen if your player is ever near y=255 or y=1? Or in a superflat world with even tighter constraint on y?
Where's the problem?

*Hug*

Posted

... to compare the coords-bundle in the config and the coords of the block. If there is match, I will spawn particles above it...

Hmmm... If all you care about is coords, then you don't need all those block states. Just run through the coords in the config looking for points whose calculated distance is less than radius from player. Vanilla Minecraft already has methods for distance.

 

For each hit you detect, spawn particles, perhaps after checking the blockstate for anything that would interfere. You'll fetch far fewer blockstates that way, and you'll be less likely to run out of memory.

 

PS: If you search radius 10 from a position at y=2, what does your code do? What happens if it passes y=0 or y=-1 in that method call? And what would happen then? (maybe nothing, but it looks dangerous)

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

Posted

Thanks to you all and thanks for your patience  :P

You helped me alot

 

Now someone must add "[solved]" to the title ;)

 

Greets from Germany  8)

*Hug*

Posted

Now someone must add "[solved]" to the title ;)

 

You can do that yourself by editing the original post.

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.

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.