Jump to content

How do i meke the redstone ore glow for exact 4 secconds (80 ticks) after been activated?


Recommended Posts

Posted

Hello

 

I want to make the redstone ore glow for exact 4 secconds (80 ticks).

So i tried this in my overridden class for the redstone ore:

Spoiler

package drachenbauer32.yellowredstonemod.blocks;

import java.util.Random;

import net.minecraft.block.BlockState;
import net.minecraft.block.RedstoneOreBlock;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.particles.RedstoneParticleData;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;

public class YellowRedstoneOreBlock extends RedstoneOreBlock
{
    private int timer;
    
    public YellowRedstoneOreBlock(Properties properties)
    {
        super(properties);
    }
    
    public void onBlockClicked(BlockState state, World worldIn, BlockPos pos, PlayerEntity player)
    {
        activate(state, worldIn, pos);
        timer = 80;
    }
    
    @Override
    public void onEntityWalk(World worldIn, BlockPos pos, Entity entityIn)
    {
        activate(worldIn.getBlockState(pos), worldIn, pos);
        timer = 80;
    }
    
    @Override
    public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit)
    {
        activate(state, world, pos);
        timer = 80;
            
        if (world.isRemote)
        {
            return ActionResultType.SUCCESS;
        }
        else
        {
            return ActionResultType.PASS;
        }
    }
    
    private static void activate(BlockState state, World world, BlockPos pos)
    {
        spawnParticles(world, pos);
        
        if (!state.get(LIT))
        {
           world.setBlockState(pos, state.with(LIT, Boolean.valueOf(true)), 3);
        }
    }
    
    @Override
    public void animateTick(BlockState state, World world, BlockPos pos, Random rand)
    {
        if (timer > 0)
        {
            timer--;
        }
        
        if (timer == 0)
        {
            world.setBlockState(pos, state.with(LIT, Boolean.valueOf(false)), 3);
        }
        
        if(state.get(LIT))
        {
            spawnParticles(world, pos);
        }
    }
    
    private static void spawnParticles(World world, BlockPos pos)
    {
        Random random = world.rand;
        
        for(Direction direction : Direction.values())
        {
            BlockPos blockpos = pos.offset(direction);
            
            if (!world.getBlockState(blockpos).isOpaqueCube(world, blockpos))
            {
                Direction.Axis direction$axis = direction.getAxis();
                double d1 = direction$axis == Direction.Axis.X ? 0.5D + 0.5625D * (double)direction.getXOffset() : (double)random.nextFloat();
                double d2 = direction$axis == Direction.Axis.Y ? 0.5D + 0.5625D * (double)direction.getYOffset() : (double)random.nextFloat();
                double d3 = direction$axis == Direction.Axis.Z ? 0.5D + 0.5625D * (double)direction.getZOffset() : (double)random.nextFloat();
                world.addParticle(new RedstoneParticleData(1.0F, 0.875F, 0.0F, 1.0F), (double)pos.getX() + d1, (double)pos.getY() + d2, (double)pos.getZ() + d3, 0.0D, 0.0D, 0.0D);
            }
        }
    }
    
    @Override
    public void tick(BlockState state, ServerWorld worldIn, BlockPos pos, Random rand)
    {
        
    }
}

But it does not exactly, what i want.

 

If i activate some blocks of that redstone ore with a few secconds delay, they switch off almost in the same moment.

If i stand on one of them and some more are activated, they all stay activated, until i leave them and wait a few secconds.

If i strike one with a sword, it only blinks short (only if one is already activated, the striked one stays activated until the other one switches off).

 

I want them glow for 4 secconds after last activating, no matter, how they are activated (step on them, rightclick them, place something on them, strike them with a weapon).

What one of them does, should not have an effect on others.

 

What must i change in my code?

Posted
1 hour ago, Drachenbauer said:

private int timer;

I'm not sure how many times you've been told, but you can not do this.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted (edited)

why not?

In my AngryBirdsMod i use a siminar way to count ticks until deflating for the inflatable bird.

Now i thaught, every block of this type, that actually exist in the world, uses it´s own instance of this class.

 

What else should i do?

Edited by Drachenbauer
Posted

No, all blocks of a given type share a single instance.

Schedule a tick with the world (specifically use World#getPendingBlockTicks and schedule there) when it gets activated and override the tick method in the block to handle deactivation.

I'm eager to learn and am prone to mistakes. Don't hesitate to tell me how I can improve.

Posted (edited)

Give this a read:

especially Problematic code #9:

Quote

Any IForgeRegistryEntry (commonly items and blocks) is singleton-like. That means that there is only once instance of your block class. There is not a new Block instance for every position in the world and there is not a new Item instance for every ItemStack. This means that you cannot store position-related things as instance fields in your block class, etc. You must use a TileEntity resp. the NBT data on ItemStack.

This applies to Items, Blocks, EntityTypes, TileEntityTypes and similar stuff.

For more info:

https://www.tutorialspoint.com/java/java_using_singleton.htm

Edited by _Cruelar_
Added explaination for singletons

My Projects:

Cruelars Triforcemod (1.12 release; 1.14 alpha soon coming)

 

Important:

As my mod is on at least 10 different third party sites without my permission, I want to warn you about that with a link to StopModReposts

Posted (edited)
16 hours ago, imacatlolol said:

No, all blocks of a given type share a single instance.

Schedule a tick with the world (specifically use World#getPendingBlockTicks and schedule there) when it gets activated and override the tick method in the block to handle deactivation.

 

I´m not sure, how exactly to use World#getPendingBlockTicks.

 

For te redstone ore, it seems like the tick method is called a bit randomly...

How do i make it call this method exactly 80 ticks after activate?

Edited by Drachenbauer
Posted (edited)
8 minutes ago, Drachenbauer said:

I´m not sure, how exactly to use World#getPendingBlockTicks.

World::getPendingBlockTicks returns an ITickList Then use ITickList::scheduleTick(BlockPos, Block, numberOfTicks)

 

Then override the Block::tick in your Block class. The world will call this method when the numberOfTicks have passed or more ticks have passed.

Edited by Animefan8888

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

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

Forge and vanilla BlockState generator.

Posted (edited)

In the method tick of this block holds only the command switch it off.

But if i go deeper with call hirachy or show references, i find something, that adds a random value.

 

How do i set the numberOfTicks to 80 ticks?

Edited by Drachenbauer
Posted
13 minutes ago, Drachenbauer said:

How do i set the numberOfTicks to 80 ticks?

In the call to ITickList::scheduleTick.

14 minutes ago, Drachenbauer said:

In the method tick of this block holds only the command switch it off.

But if i go deeper with call hirachy or show references, i find something, that adds a random value.

I'm not sure what you are saying here.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

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

Forge and vanilla BlockState generator.

Posted (edited)

You sayd:

Quote

ITickList::scheduleTick(BlockPos, Block, numberOfTicks)

But for me the middle parameter is not Block, it´s Object.

What must i put there?

 

And to the thing, what you don´t understand:

For the original redstone ore, it goes a bit random, how long it waits until it switches off.

But that random value is not given in the RedstoneOreBlock class, it´s, where tick is called.

tick is called by randomTick of the basic Block class.

And because of that name i think, that one is called randomly, what gives the random effect of the vanilla RedstoneOre.

Edited by Drachenbauer
Posted
7 minutes ago, Drachenbauer said:

For the original redstone ore, it goes a bit random, how long it waits until it switches off.

But that random value is not given in that block class, it´s, where tick is called.

It's random because when the Blocks.REDSTONE_ORE instance is created it looks like this

new RedstoneOreBlock(Block.Properties.create(...).tickRandomly()...)...

That tick randomly lets the game know to call the tick function randomly.

8 minutes ago, Drachenbauer said:

But for me the middle parameter is not Block, it´s Object.

What must i put there?

Show all of your code.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

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

Forge and vanilla BlockState generator.

Posted
package drachenbauer32.yellowredstonemod.blocks;

import java.util.Random;

import net.minecraft.block.BlockState;
import net.minecraft.block.RedstoneOreBlock;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.particles.RedstoneParticleData;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.world.ITickList;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;

public class YellowRedstoneOreBlock extends RedstoneOreBlock
{
    
    public YellowRedstoneOreBlock(Properties properties)
    {
        super(properties);
    }
    
    public void onBlockClicked(BlockState state, World worldIn, BlockPos pos, PlayerEntity player)
    {
        activate(state, worldIn, pos);
    }
    
    @Override
    public void onEntityWalk(World worldIn, BlockPos pos, Entity entityIn)
    {
        activate(worldIn.getBlockState(pos), worldIn, pos);
    }
    
    @Override
    public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit)
    {
        activate(state, world, pos);
            
        if (world.isRemote)
        {
            return ActionResultType.SUCCESS;
        }
        else
        {
            return ActionResultType.PASS;
        }
    }
    
    private static void activate(BlockState state, World world, BlockPos pos)
    {
        spawnParticles(world, pos);
        
        if (!state.get(LIT))
        {
           ITickList tickList = world.getPendingBlockTicks();
           tickList.scheduleTick(pos, itemIn, 80);
           world.setBlockState(pos, state.with(LIT, Boolean.valueOf(true)), 3);
        }
    }
    
    @Override
    public void animateTick(BlockState state, World world, BlockPos pos, Random rand)
    {
        if(state.get(LIT))
        {
            spawnParticles(world, pos);
        }
    }
    
    private static void spawnParticles(World world, BlockPos pos)
    {
        Random random = world.rand;
        
        for(Direction direction : Direction.values())
        {
            BlockPos blockpos = pos.offset(direction);
            
            if (!world.getBlockState(blockpos).isOpaqueCube(world, blockpos))
            {
                Direction.Axis direction$axis = direction.getAxis();
                double d1 = direction$axis == Direction.Axis.X ? 0.5D + 0.5625D * (double)direction.getXOffset() : (double)random.nextFloat();
                double d2 = direction$axis == Direction.Axis.Y ? 0.5D + 0.5625D * (double)direction.getYOffset() : (double)random.nextFloat();
                double d3 = direction$axis == Direction.Axis.Z ? 0.5D + 0.5625D * (double)direction.getZOffset() : (double)random.nextFloat();
                world.addParticle(new RedstoneParticleData(1.0F, 0.875F, 0.0F, 1.0F), (double)pos.getX() + d1, (double)pos.getY() + d2, (double)pos.getZ() + d3, 0.0D, 0.0D, 0.0D);
            }
        }
    }
    
    @Override
    public void tick(BlockState state, ServerWorld worldIn, BlockPos pos, Random rand)
    {
        
    }
}

 

It´s in the method "activate".

Posted
2 minutes ago, Drachenbauer said:

ITickList tickList = world.getPendingBlockTicks();

ITickList is a generic class so what you really want is ITickList<Block>

 

And thus itemIn becomes Block instead of Object.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

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

Forge and vanilla BlockState generator.

Posted

I found this in just this seccond.

But i still cannot put the name of my block class in there.

Should i use the name from the registration of this block (in my case with .get(), because it is a RegistryObject)?

 

Posted
2 minutes ago, Drachenbauer said:

Should i use the name from the registration of this block (in my case with .get(), because it is a RegistryObject)?

What are you talking about? You have access to the Block object already. Use the "this" keyword.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

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

Forge and vanilla BlockState generator.

Posted
Just now, Drachenbauer said:

There came the error: that this keyword cannot be used the static way.

My bad forgot your activate method was static. You have the BlockState parameter use BlockState::getBlock

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

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

Forge and vanilla BlockState generator.

Posted
Quote

It's random because when the Blocks.REDSTONE_ORE instance is created it looks like this


new RedstoneOreBlock(Block.Properties.create(...).tickRandomly()...)...

That tick randomly lets the game know to call the tick function randomly.

Then it must be fine, if i delete it from my registration for overriding the block.

Posted
1 minute ago, Drachenbauer said:

Then it must be fine, if i delete it from my registration for overriding the block.

Yes you definitely don't want to have your Block tick randomly.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

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

Forge and vanilla BlockState generator.

Posted (edited)

Now it stays activated all the time.

 

In thr RedstoneOreBlock there is already the deacttivation in the method "thick".

so atfirst i removed that method override.

 

Must i override it and put something more into it?

 

Edit if i activate them in the actual test, it works, but there are some activated from a prvious test.

Why they stay activated?

Edited by Drachenbauer
Posted
3 minutes ago, Drachenbauer said:

Why they stay activated?

Because they only tick when you tell them to tick. And you only ever tell them to tick when they become activated.

VANILLA MINECRAFT CLASSES ARE THE BEST RESOURCES WHEN MODDING

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

Forge and vanilla BlockState generator.

Posted (edited)
package drachenbauer32.yellowredstonemod.blocks;

import java.util.Random;

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.RedstoneOreBlock;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.particles.RedstoneParticleData;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.world.ITickList;
import net.minecraft.world.World;

public class YellowRedstoneOreBlock extends RedstoneOreBlock
{
    
    public YellowRedstoneOreBlock(Properties properties)
    {
        super(properties);
    }
    
    public void onBlockClicked(BlockState state, World worldIn, BlockPos pos, PlayerEntity player)
    {
        activate(state, worldIn, pos);
    }
    
    @Override
    public void onEntityWalk(World worldIn, BlockPos pos, Entity entityIn)
    {
        activate(worldIn.getBlockState(pos), worldIn, pos);
    }
    
    @Override
    public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit)
    {
        activate(state, world, pos);
            
        if (world.isRemote)
        {
            return ActionResultType.SUCCESS;
        }
        else
        {
            return ActionResultType.PASS;
        }
    }
    
    private static void activate(BlockState state, World world, BlockPos pos)
    {
        spawnParticles(world, pos);
        ITickList<Block> tickList = world.getPendingBlockTicks();
        tickList.scheduleTick(pos, state.getBlock(), 80);
        
        if (!state.get(LIT))
        {
            world.setBlockState(pos, state.with(LIT, Boolean.valueOf(true)), 3);
        }
    }
    
    @Override
    public void animateTick(BlockState state, World world, BlockPos pos, Random rand)
    {
        if(state.get(LIT))
        {
            spawnParticles(world, pos);
        }
    }
    
    private static void spawnParticles(World world, BlockPos pos)
    {
        Random random = world.rand;
        
        for(Direction direction : Direction.values())
        {
            BlockPos blockpos = pos.offset(direction);
            
            if (!world.getBlockState(blockpos).isOpaqueCube(world, blockpos))
            {
                Direction.Axis direction$axis = direction.getAxis();
                double d1 = direction$axis == Direction.Axis.X ? 0.5D + 0.5625D * (double)direction.getXOffset() : (double)random.nextFloat();
                double d2 = direction$axis == Direction.Axis.Y ? 0.5D + 0.5625D * (double)direction.getYOffset() : (double)random.nextFloat();
                double d3 = direction$axis == Direction.Axis.Z ? 0.5D + 0.5625D * (double)direction.getZOffset() : (double)random.nextFloat();
                world.addParticle(new RedstoneParticleData(1.0F, 0.875F, 0.0F, 1.0F), (double)pos.getX() + d1, (double)pos.getY() + d2, (double)pos.getZ() + d3, 0.0D, 0.0D, 0.0D);
            }
        }
    }
}

 

And how can i make it activate, if i run into it, or leftclick it with a sword or other tool?

Edited by Drachenbauer

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() ); } }  
    • Do you use features of inventory profiles next (ipnext) or is there a change without it?
  • Topics

×
×
  • Create New...

Important Information

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