Jump to content

Soundplaying problems [1.8]


ItsAMysteriousYT

Recommended Posts

Hey there, im wondering if im doing something wrong when i try to play sounds. I think they have to be played on the client, right? But when i do this, it just keeps silent.

Im doing this in the onUpdate method of my entity class like this:

 

if(isClient()){

  Minecraft.getMinecraft().getSoundHandler().playSound(this.startsound);

}

 

The startsound is an instane of MovingSound and is defined when the vehicle is being loaded from a textfile.

What am i doing wrong?

Link to comment
Share on other sites

if(isClient()){

  Minecraft.getMinecraft().getSoundHandler().playSound(this.startsound);

}

 

Set a breakpoint in there and walk through in the debugger. If it never even hits your breakpoint, then your problem is elsewhere.

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.

Link to comment
Share on other sites

Sorry that u didn't reply - I managed to get the sound playing now like this:

 

 

private void playSounds() {

VehicleFile file = getFile();

// Only playing enginesound if startsound and stopsound are not playing

if (ticksSinceEntered == 0 && ticksSinceLeft == 0 && loopingsoundposition == 0 && riddenByEntity != null) {

loopingsoundposition = runsound.length;

worldObj.playSoundAtEntity(this, "reallifemod:" + runsound.getSoundLocation().getResourcePath(), 1, 1);

}

 

if (throttle > 0) {

if (loopingsoundposition == 0) {

loopingsoundposition = throttlesound.length;

worldObj.playSoundAtEntity(this, "reallifemod:" + throttlesound.getSoundLocation().getResourcePath(), 1,

1);

 

// PacketPlaySound.sendSoundPacket((float) posX, (float) posY,

// (float) posZ, 10f, worldObj.provider.getDimensionId(),

// throttlesound.getSoundLocation().getResourcePath(), 1f);

}

}

 

if (ticksSinceEntered == 1) {

if (startsound != null && loopingsoundposition == 0) {

}

}

 

}

 

 

 

But what i actually trying to do is using my CustomSounds so i can change pitch and stuff, but it errors with a HashByMapError because the sound instance is already excisting. How can i solve this problem?

Link to comment
Share on other sites

You have a bunch of undeclared variables in your program. Vars like loopingsoundposition need to be declared somewhere, but I don't see them.

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.

Link to comment
Share on other sites

Also, the two code snippets you have provided are very incompatible with each other:

if (!worldObj.isRemote) { // true when on SERVER
    playSounds();
}

if(isClient()){ // probably true when on CLIENT
   Minecraft.getMinecraft().getSoundHandler().playSound(this.startsound);
}

Assuming that the 2nd snippet is in your #playSounds method, there is a big problem. Otherwise, as everyone else has said, you need to post your actual code if you expect to receive help, not just tiny snippets of it. We need the full context of what's calling what where.

Link to comment
Share on other sites

As i already said, i managed to get it working and the snippets from the first time did not work. Those from the second time work. And for the code, this is the whole class:

 

 

 

package itsamysterious.mods.reallifemod.core.vehicles;

 

import org.lwjgl.input.Keyboard;

import org.lwjgl.util.vector.Vector3f;

 

import io.netty.buffer.ByteBuf;

import itsamysterious.mods.reallifemod.RealLifeMod;

import itsamysterious.mods.reallifemod.api.IControllable;

import itsamysterious.mods.reallifemod.core.packets.ControlableInputPacket;

import itsamysterious.mods.reallifemod.core.packets.PacketDriveableKeyHeld;

import itsamysterious.mods.reallifemod.core.packets.UpdateControlPackage;

import itsamysterious.mods.reallifemod.core.sounds.CustomSound;

import net.minecraft.block.Block;

import net.minecraft.client.Minecraft;

import net.minecraft.entity.Entity;

import net.minecraft.entity.player.EntityPlayer;

import net.minecraft.init.Blocks;

import net.minecraft.nbt.NBTTagCompound;

import net.minecraft.util.AxisAlignedBB;

import net.minecraft.util.Vec3;

import net.minecraft.util.Vec3i;

import net.minecraft.world.World;

import net.minecraftforge.fml.common.network.ByteBufUtils;

import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint;

import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData;

 

public class EntityDriveable extends Entity implements IControllable, IEntityAdditionalSpawnData {

 

private String filename;

public double throttle;

 

public double serverPosX, serverPosY, serverPosZ;

// Durch die zwei unabhängigen geschwindigkeiten können die räder

// durchdrehen!

public double motorspeed;

// will be the motorspeed reduced by the forces.

public double actualspeed;

public float steeringAngle;

public float wheelsAngle;

 

public boolean isLightOn;

 

public EntitySeat[] seats;

public EntityWheel[] wheels;

public float rotationRoll;

public float prevRotationRoll;

public double fuellevel;

 

public CustomRotationAxes axes;

public CustomRotationAxes prevAxes;

 

public CustomSound startsound;

public CustomSound stopsound;

public CustomSound runsound;

public CustomSound throttlesound;

 

private boolean syncFromServer;

private int serverPositionTransitionTicker;

private float serverYaw;

private float serverPitch;

private Vector3f angularVelocity;

private float serverRoll;

private boolean leftMouseHeld;

private boolean rightMouseHeld;

 

/**

* All the stuff for playing the sounds right

*/

public int ticksSinceLeft = 0;

public int ticksSinceEntered = 0;

public int loopingsoundposition;

 

public EntityDriveable(World worldIn) {

super(worldIn);

axes = new CustomRotationAxes();

preventEntitySpawning = true;

setSize(1F, 1F);

ignoreFrustumCheck = true;

renderDistanceWeight = 200D;

}

 

public EntityDriveable(World world, VehicleFile f, double x, double y, double z, EntityPlayer placer) {

this(world);

filename = f.vehicleName;

setPosition(x, y, z);

axes.setAngles(rotationYaw, rotationPitch, rotationRoll);

initFile(f, false);

}

 

protected void initFile(VehicleFile f, boolean isClient) {

 

/*

* seats = new EntitySeat[f.numDrivers]; for (int i = 0; i <

* seats.length; i++) {

*

* if (!isClient) { seats = new EntitySeat(worldObj, this, i);

* worldObj.spawnEntityInWorld(seats); } }

*/

 

// Initialisation of wheels

 

wheels = new EntityWheel[f.wheelPositions.length];

for (int i = 0; i < wheels.length; i++) {

if (!isClient) {

wheels = new EntityWheel(worldObj, this, i);

worldObj.spawnEntityInWorld(wheels);

}

}

 

stepHeight = f.wheelStepHeight;

this.startsound = new CustomSound(f.startsound.getSoundLocation(), f.startsound.length);

this.stopsound = new CustomSound(f.stopsound.getSoundLocation(), f.stopsound.length);

this.throttlesound = new CustomSound(f.throttlesound.getSoundLocation(), f.throttlesound.length);

this.runsound = new CustomSound(f.enginesound.getSoundLocation(), f.enginesound.length);

 

}

 

public void setPosition(double x, double y, double z) {

super.setPosition(x, y, z);

if (isClient()) {

RealLifeMod.network.sendToServer(new UpdateControlPackage());

}

}

 

// Called on client

@Override

public void writeSpawnData(ByteBuf data) {

ByteBufUtils.writeUTF8String(data, this.filename);

data.writeFloat(axes.getYaw());

data.writeFloat(axes.getPitch());

data.writeFloat(axes.getRoll());

}

 

// Called on client

@Override

public void readSpawnData(ByteBuf data) {

try {

filename = ByteBufUtils.readUTF8String(data);

 

axes.setAngles(data.readFloat(), data.readFloat(), data.readFloat());

prevRotationYaw = axes.getYaw();

prevRotationPitch = axes.getPitch();

prevRotationRoll = axes.getRoll();

// Warum nicht hier initFIle? Dann ist die rotation korrekt!

initFile(getFile(), true);

 

} catch (Exception e) {

RealLifeMod.log("Did not work!");

super.setDead();

e.printStackTrace();

}

}

 

@Override

public void func_180426_a(double d, double d1, double d2, float f, float f1, int i, boolean b) {

if (ticksExisted > 1)

return;

if (riddenByEntity instanceof EntityPlayer && RealLifeMod.proxy.isThePlayer((EntityPlayer) riddenByEntity)) {

} else {

if (syncFromServer) {

serverPositionTransitionTicker = i + 5;

} else {

double var10 = d - posX;

double var12 = d1 - posY;

double var14 = d2 - posZ;

double var16 = var10 * var10 + var12 * var12 + var14 * var14;

 

if (var16 <= 1.0D) {

return;

}

 

serverPositionTransitionTicker = 3;

}

serverPosX = d;

serverPosY = d1;

serverPosZ = d2;

serverYaw = f;

serverPitch = f1;

}

}

 

public void setPositionRotationAndMotion(double x, double y, double z, float yaw, float pitch, float roll,

double motX, double motY, double motZ, float velYaw, float velPitch, float velRoll, float throt,

float steeringYaw) {

if (worldObj.isRemote) {

serverPosX = x;

serverPosY = y;

serverPosZ = z;

serverYaw = yaw;

serverPitch = pitch;

serverRoll = roll;

serverPositionTransitionTicker = 5;

} else {

setPosition(x, y, z);

prevRotationYaw = yaw;

prevRotationPitch = pitch;

prevRotationRoll = roll;

setRotation(yaw, pitch, roll);

}

// Set the motions regardless of side.

motionX = motX;

motionY = motY;

motionZ = motZ;

angularVelocity = new Vector3f(velYaw, velPitch, velRoll);

throttle = throt;

}

 

private void setRotation(float yaw, float pitch, float roll) {

super.setRotation(yaw, pitch);

axes.setAngles(yaw, pitch, roll);

}

 

// Called on Server

@Override

protected void readEntityFromNBT(NBTTagCompound tagCompund) {

filename = tagCompund.getString("VehicleName");

 

 

prevRotationYaw = tagCompund.getFloat("RotationYaw");

prevRotationPitch = tagCompund.getFloat("RotationPitch");

prevRotationRoll = tagCompund.getFloat("RotationRoll");

axes = new CustomRotationAxes(prevRotationYaw, prevRotationPitch, prevRotationRoll);

initFile(Vehicles.get(filename), false);

 

fuellevel = tagCompund.getDouble("Fuel");

 

}

 

// Called on Server

@Override

protected void writeEntityToNBT(NBTTagCompound tagCompund) {

tagCompund.setString("VehicleName", filename);

tagCompund.setDouble("Fuel", fuellevel);

tagCompund.setFloat("RotationYaw", rotationYaw);

tagCompund.setFloat("RotationPitch", rotationPitch);

tagCompund.setFloat("RotationRoll", rotationRoll);

 

}

 

@Override

public AxisAlignedBB getCollisionBox(Entity entity) {

return null;// entity.boundingBox;

}

 

@Override

public boolean canBePushed() {

return false;

}

 

@Override

public void onCollideWithPlayer(EntityPlayer par1EntityPlayer) {

// Do nothing. Like a boss.

// : perhaps send the player flying??

// Sounds good. ^

}

 

@Override

public boolean canBeCollidedWith() {

return !isDead;

}

 

@Override

public void onUpdate() {

super.onUpdate();

VehicleFile file = getFile();

 

if (file == null) {

return;

}

 

if (!worldObj.isRemote) {

 

/*

* for (int i = 0; i < getFile().numDrivers + 1; i++) { if (seats

* == null || !seats.addedToChunk) { seats = new

* EntitySeat(worldObj, this, i);

* worldObj.spawnEntityInWorld(seats); } }

*/

 

for (int i = 0; i < file.wheelPositions.length; i++) {

if (wheels == null || !wheels.addedToChunk) {

wheels = new EntityWheel(worldObj, this, i);

worldObj.spawnEntityInWorld(wheels);

}

}

 

}

 

prevRotationYaw = axes.getYaw();

prevRotationPitch = axes.getPitch();

prevRotationRoll = axes.getRoll();

 

prevAxes = axes.clone();

 

simulateValues();

if (riddenByEntity != null && riddenByEntity.isDead) {

riddenByEntity = null;

}

 

if (riddenByEntity != null && isDead) {

riddenByEntity.mountEntity(null);

}

if (riddenByEntity != null)

riddenByEntity.fallDistance = 0F;

 

boolean playerIsDrivingThis = worldObj.isRemote && riddenByEntity != null

&& riddenByEntity instanceof EntityPlayer && riddenByEntity == Minecraft.getMinecraft().thePlayer;// seats[0]

 

// EntityPlayer;

if (playerIsDrivingThis) {

// if(isClient())

// RealLifeMod.network.sendToServer(new UpdateControlPackage(this));

// Setting the correct position to the position that is already

// there to prevent mistakes

serverPosX = posX;

serverPosY = posY;

serverPosZ = posZ;

if (!isClient())

if (ticksSinceEntered > 0 && ticksSinceEntered < 5) {

ticksSinceEntered++;

}

 

if (ticksSinceEntered == 5)

ticksSinceEntered = 0;

 

}

 

if (isClient()) {

if (ticksSinceLeft > 0)

ticksSinceLeft--;

 

if (ticksSinceEntered > 0)

ticksSinceEntered--;

}

 

if (loopingsoundposition > 0) {

loopingsoundposition--;

}

 

if (!worldObj.isRemote) {

playSounds();

 

}

 

if (!worldObj.isRemote && ticksExisted % 5 == 0) {

 

RealLifeMod.network.sendToAllAround(new UpdateControlPackage(this),

new TargetPoint(dimension, posX, posY, posZ, 10));

}

 

}

 

public void simulateValues() {

}

 

private void playSounds() {

VehicleFile file = getFile();

// Only playing enginesound if startsound and stopsound are not playing

if (ticksSinceEntered == 0 && ticksSinceLeft == 0 && loopingsoundposition == 0 && riddenByEntity != null) {

loopingsoundposition = runsound.length;

worldObj.playSoundAtEntity(this, "reallifemod:" + runsound.getSoundLocation().getResourcePath(), 1, 1f);

}

 

if (throttle > 0) {

if (loopingsoundposition == 0) {

loopingsoundposition = throttlesound.length;

worldObj.playSoundAtEntity(this, "reallifemod:" + throttlesound.getSoundLocation().getResourcePath(), 1,

1);

 

// PacketPlaySound.sendSoundPacket((float) posX, (float) posY,

// (float) posZ, 10f, worldObj.provider.getDimensionId(),

// throttlesound.getSoundLocation().getResourcePath(), 1f);

}

}

 

if (ticksSinceEntered == 1) {

if (startsound != null && loopingsoundposition == 0) {

}

}

 

}

 

public void setAngles(float f, float g, float h) {

rotationYaw = f;

rotationPitch = g;

rotationRoll = h;

}

 

@Override

public boolean interactFirst(EntityPlayer playerIn) {

if (worldObj == null)

return false;

if (!worldObj.isRemote) {

worldObj.playSoundAtEntity(this, "reallifemod:" + startsound.getSoundLocation().getResourcePath(), 1,

(float) this.actualspeed * 100);

 

} else {

// Minecraft.getMinecraft().getSoundHandler().playSound(CustomSound.getSoundWithPosition(getFile().startsound.getSoundLocation().getResourcePath(),

// (float)posX, (float)posY, (float)posZ, 1, 1));

}

playerIn.rotationYaw=this.rotationYaw;

playerIn.rotationYawHead=this.rotationYaw;

 

playerIn.mountEntity(this);

 

/** Setting ticksSinceEntered to 1 so onUpdate starts counting */

ticksSinceEntered = startsound.length/2-20;

 

return true;

}

 

@Override

public void updateRiderPosition() {

EntityPlayer p=(EntityPlayer)riddenByEntity;

Vector3f riderPosition = axes.findLocalVectorGlobally(getFile().seatPositions[0]);

p.setAir(1);

p.setPosition(posX + riderPosition.x, posY + riderPosition.y, posZ + riderPosition.z);

}

 

protected boolean isClient() {

return !this.worldObj.isRemote;

}

 

public VehicleFile getFile() {

return Vehicles.get(filename);

}

 

protected Block findBlockUnderVehicle() {

if (worldObj != null)

return worldObj.getBlockState(getPosition().subtract(new Vec3i(0, 1, 0))).getBlock();

else

return Blocks.air;

}

 

public Vector3f getPositionVectorFloat() {

return new Vector3f((float) posX, (float) posY, (float) posZ);

}

 

public void rotateYaw(float rotateBy) {

if (Math.abs(rotateBy) < 0.01F)

return;

rotationYaw = rotateBy;

updatePrevAngles();

}

 

public void updatePrevAngles() {

// Correct angles that crossed the +/- 180 line, so that rendering

// doesnt make them swing 360 degrees in one tick.

double dYaw = rotationYaw - prevRotationYaw;

if (dYaw > 180)

prevRotationYaw += 360F;

if (dYaw < -180)

prevRotationYaw -= 360F;

 

double dPitch = rotationPitch - prevRotationPitch;

if (dPitch > 180)

prevRotationPitch += 360F;

if (dPitch < -180)

prevRotationPitch -= 360F;

 

double dRoll = rotationRoll - prevRotationRoll;

if (dRoll > 180)

prevRotationRoll += 360F;

if (dRoll < -180)

prevRotationRoll -= 360F;

axes.setAngles(rotationYaw, rotationPitch, rotationRoll);

}

 

@Override

protected void entityInit() {

 

}

 

@Override

public void setDead() {

super.setDead();

}

 

public Vector3f rotate(Vector3f inVec) {

return axes.findLocalVectorGlobally(inVec);

}

 

/**

* Takes a vector (such as the origin of a seat / gun) and translates it

* from local coordinates to global coordinates

*/

public Vector3f rotate(Vec3 inVec) {

return rotate(inVec.xCoord, inVec.yCoord, inVec.zCoord);

}

 

/**

* Takes a vector (such as the origin of a seat / gun) and translates it

* from local coordinates to global coordinates

*/

public Vector3f rotate(double x, double y, double z) {

return rotate(new Vector3f((float) x, (float) y, (float) z));

}

 

@Override

public void onMouseMoved(int deltaX, int deltaY) {

}

 

@Override

public boolean pressKey(int key, EntityPlayer player) {

VehicleFile file = getFile();

if (worldObj.isRemote && (key == Keyboard.KEY_W || key == 5)) {

// SendKeyPacketToServer

/**

* If player dismounts, set tickssinceleft to 1 for the stopping

* sound

*/

if (key == 6) {

loopingsoundposition = 5;

if (riddenByEntity == null && loopingsoundposition == 5) {

if (stopsound != null && loopingsoundposition == 0) {

worldObj.playSoundAtEntity(this,

"reallifemod:" + startsound.getSoundLocation().getResourcePath(), 1, 1);

}

}

}

 

RealLifeMod.network.sendToServer(new ControlableInputPacket());

}

return false;

}

 

@Override

public void updateKeyHeldState(int key, boolean held) {

if (worldObj.isRemote) {

RealLifeMod.network.sendToServer(new PacketDriveableKeyHeld(key, held));

}

switch (key) {

case 9:

leftMouseHeld = held;

break;

case 8:

rightMouseHeld = held;

break;

}

}

 

@Override

public Entity getControllingEntity() {

return riddenByEntity;

}

 

@Override

public boolean isDead() {

return isDead;

}

 

@Override

public float getPlayerRoll() {

return axes.getRoll();

}

 

@Override

public float getPrevPlayerRoll() {

return prevAxes.getRoll();

}

 

}

 

 

 

Link to comment
Share on other sites

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

    • I am creating a mod that adds new armor sets and changes how armor sets are crafted. When the player interacts with the block it fails to open the gui, but I get no error or stacktrace. All of my registration classes are being called correctly. LightArmorBenchScreen's constructor, render, and renderbg methods are not being called at all. Here is the code: package net.leeveygames.celestial.blocks.custom; import net.leeveygames.celestial.Celestial; import net.leeveygames.celestial.blocks.entity.CelestialBlockEntities; import net.leeveygames.celestial.blocks.entity.LightArmorBenchBlockEntity; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.network.NetworkHooks; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class LightArmorBenchBlock extends BaseEntityBlock { public static final VoxelShape SHAPE = Block.box(0, 0, 0, 16, 12, 16); public LightArmorBenchBlock(Properties pProperties) { super(pProperties); } @Override public VoxelShape getShape(BlockState pState, BlockGetter pLevel, BlockPos pPos, CollisionContext pContext) { return SHAPE; } @Override public RenderShape getRenderShape(BlockState pState) { return RenderShape.MODEL; } @Override public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) { if (pState.getBlock() != pNewState.getBlock()) { BlockEntity blockEntity = pLevel.getBlockEntity(pPos); if (blockEntity instanceof LightArmorBenchBlockEntity) { ((LightArmorBenchBlockEntity) blockEntity).drops(); } } super.onRemove(pState, pLevel, pPos, pNewState, pIsMoving); } @NotNull @Override public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand, BlockHitResult pHit) { if(pLevel.isClientSide()) return InteractionResult.SUCCESS; BlockEntity be = pLevel.getBlockEntity(pPos); if (be instanceof LightArmorBenchBlockEntity blockEntity) { ServerPlayer player = (ServerPlayer)pPlayer; Celestial.LOGGER.info("Opening Screen."); NetworkHooks.openScreen(player, blockEntity, pPos); } return InteractionResult.CONSUME; } @Nullable @Override public BlockEntity newBlockEntity(BlockPos pPos, BlockState pState) { return new LightArmorBenchBlockEntity(pPos, pState); } @Nullable @Override public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level pLevel, BlockState pState, BlockEntityType<T> pBlockEntityType) { if(pLevel.isClientSide()) { return null; } return createTickerHelper(pBlockEntityType, CelestialBlockEntities.LIGHT_ARMOR_BENCH_BLOCK_ENTITY.get(), (pLevel1, pPos, pState1, pBlockEntity) -> pBlockEntity.tick(pLevel1, pPos, pState1)); } }   package net.leeveygames.celestial.screen; import net.leeveygames.celestial.Celestial; import net.leeveygames.celestial.blocks.CelestialBlocks; import net.leeveygames.celestial.blocks.entity.LightArmorBenchBlockEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.*; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.items.SlotItemHandler; public class LightArmorBenchMenu extends AbstractContainerMenu { public final LightArmorBenchBlockEntity blockEntity; private final Level level; public LightArmorBenchMenu(int pContainerId, Inventory inv, FriendlyByteBuf extraData) { this(pContainerId, inv, inv.player.level().getBlockEntity(extraData.readBlockPos())); Celestial.LOGGER.info("Creating Light Armor Bench Menu. Client"); } public LightArmorBenchMenu(int pContainerId, Inventory inv, BlockEntity entity) { super(CelestialMenuTypes.LIGHT_ARMOR_BENCH_MENU.get(), pContainerId); Celestial.LOGGER.info("Creating Light Armor Bench Menu. Server"); checkContainerSize(inv, 2); blockEntity = ((LightArmorBenchBlockEntity) entity); this.level = inv.player.level(); addPlayerInventory(inv); addPlayerHotbar(inv); createLightArmorBenchSlots(blockEntity); } private void createLightArmorBenchSlots(LightArmorBenchBlockEntity blockEntity) { Celestial.LOGGER.info("Creating Light Armor Bench Slots."); this.blockEntity.getCapability(ForgeCapabilities.ITEM_HANDLER).ifPresent(iItemHandler -> { this.addSlot(new SlotItemHandler(iItemHandler, 0, 11, 15)); this.addSlot(new SlotItemHandler(iItemHandler, 1, 82, 33)); this.addSlot(new SlotItemHandler(iItemHandler, 2, 133, 33)); }); } // CREDIT GOES TO: diesieben07 | https://github.com/diesieben07/SevenCommons // must assign a slot number to each of the slots used by the GUI. // For this container, we can see both the tile inventory's slots as well as the player inventory slots and the hotbar. // Each time we add a Slot to the container, it automatically increases the slotIndex, which means // 0 - 8 = hotbar slots (which will map to the InventoryPlayer slot numbers 0 - 8) // 9 - 35 = player inventory slots (which map to the InventoryPlayer slot numbers 9 - 35) // 36 - 44 = TileInventory slots, which map to our TileEntity slot numbers 0 - 8) private static final int HOTBAR_SLOT_COUNT = 9; private static final int PLAYER_INVENTORY_ROW_COUNT = 3; private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9; private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT; private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT; private static final int VANILLA_FIRST_SLOT_INDEX = 0; private static final int TE_INVENTORY_FIRST_SLOT_INDEX = VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT; // THIS YOU HAVE TO DEFINE! private static final int TE_INVENTORY_SLOT_COUNT = 2; // must be the number of slots you have! @Override public ItemStack quickMoveStack(Player playerIn, int pIndex) { Slot sourceSlot = slots.get(pIndex); if (sourceSlot == null || !sourceSlot.hasItem()) return ItemStack.EMPTY; //EMPTY_ITEM ItemStack sourceStack = sourceSlot.getItem(); ItemStack copyOfSourceStack = sourceStack.copy(); // Check if the slot clicked is one of the vanilla container slots if (pIndex < VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT) { // This is a vanilla container slot so merge the stack into the tile inventory if (!moveItemStackTo(sourceStack, TE_INVENTORY_FIRST_SLOT_INDEX, TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT, false)) { return ItemStack.EMPTY; // EMPTY_ITEM } } else if (pIndex < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT) { // This is a TE slot so merge the stack into the players inventory if (!moveItemStackTo(sourceStack, VANILLA_FIRST_SLOT_INDEX, VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT, false)) { return ItemStack.EMPTY; } } else { System.out.println("Invalid slotIndex:" + pIndex); return ItemStack.EMPTY; } // If stack size == 0 (the entire stack was moved) set slot contents to null if (sourceStack.getCount() == 0) { sourceSlot.set(ItemStack.EMPTY); } else { sourceSlot.setChanged(); } sourceSlot.onTake(playerIn, sourceStack); return copyOfSourceStack; } @Override public boolean stillValid(Player pPlayer) { return stillValid(ContainerLevelAccess.create(level, blockEntity.getBlockPos()), pPlayer, CelestialBlocks.LIGHT_ARMOR_BENCH.get()); } private void addPlayerInventory(Inventory playerInventory) { Celestial.LOGGER.info("Creating Player Inventory."); for (int i = 0; i < 3; ++i) { for (int l = 0; l < 9; ++l) { this.addSlot(new Slot(playerInventory, l + i * 9 + 9, 8 + l * 18, 84 + i * 18)); } } } private void addPlayerHotbar(Inventory playerInventory) { Celestial.LOGGER.info("Creating Player Hotbar."); for (int i = 0; i < 9; ++i) { this.addSlot(new Slot(playerInventory, i, 8 + i * 18, 142)); } } }   package net.leeveygames.celestial.screen; import com.mojang.blaze3d.systems.RenderSystem; import net.leeveygames.celestial.Celestial; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory; public class LightArmorBenchScreen extends AbstractContainerScreen<LightArmorBenchMenu> { private static final ResourceLocation TEXTURE = new ResourceLocation(Celestial.MOD_ID, "textures/gui/LightArmorBenchGUI.png"); public LightArmorBenchScreen(LightArmorBenchMenu pMenu, Inventory pPlayerInventory, Component pTitle) { super(pMenu, pPlayerInventory, pTitle); Celestial.LOGGER.info("Creating Light Armor Bench Screen."); this.imageWidth = 176; this.imageHeight = 166; } @Override protected void init() { Celestial.LOGGER.info("Screen init."); super.init(); } @Override protected void renderBg(GuiGraphics guiGraphics, float pPartialTick, int pMouseX, int pMouseY) { Celestial.LOGGER.info("Render Background Method."); RenderSystem.setShader(GameRenderer::getPositionTexShader); RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.setShaderTexture(0, TEXTURE); guiGraphics.blit(TEXTURE, this.leftPos, this.topPos, 0, 0, this.imageWidth, this.imageHeight); } @Override public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float delta) { Celestial.LOGGER.info("Render Method."); renderBackground(guiGraphics); super.render(guiGraphics, mouseX, mouseY, delta); renderTooltip(guiGraphics, mouseX, mouseY); } }   package net.leeveygames.celestial.blocks.entity; import net.leeveygames.celestial.screen.LightArmorBenchMenu; import net.minecraft.client.gui.screens.inventory.FurnaceScreen; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.Container; import net.minecraft.world.Containers; import net.minecraft.world.MenuProvider; import net.minecraft.world.SimpleContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ContainerData; import net.minecraft.world.inventory.FurnaceMenu; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemStackHandler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class LightArmorBenchBlockEntity extends BlockEntity implements MenuProvider { private final ItemStackHandler itemHandler = new ItemStackHandler(3) { @Override protected void onContentsChanged(int slot) { super.onContentsChanged(slot); LightArmorBenchBlockEntity.this.setChanged(); } }; private static final int INPUT_SLOT = 0; private static final int OUTPUT_SLOT = 1; private LazyOptional<IItemHandler> lazyItemHandler = LazyOptional.empty(); public LightArmorBenchBlockEntity(BlockPos pPos, BlockState pBlockState) { super(CelestialBlockEntities.LIGHT_ARMOR_BENCH_BLOCK_ENTITY.get(), pPos, pBlockState); } @Override public @NotNull <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) { if(cap == ForgeCapabilities.ITEM_HANDLER) { return lazyItemHandler.cast(); } return super.getCapability(cap, side); } @Override public void onLoad() { super.onLoad(); lazyItemHandler = LazyOptional.of(() -> itemHandler); } @Override public void invalidateCaps() { super.invalidateCaps(); lazyItemHandler.invalidate(); } public void drops() { SimpleContainer inventory = new SimpleContainer(itemHandler.getSlots()); for(int i = 0; i < itemHandler.getSlots(); i++) { inventory.setItem(i, itemHandler.getStackInSlot(i)); } Containers.dropContents(this.level, this.worldPosition, inventory); } @Override public Component getDisplayName() { return Component.translatable("block.celestial.light_armor_bench"); } @Nullable @Override public AbstractContainerMenu createMenu(int pContainerId, Inventory pPlayerInventory, Player pPlayer) { return new LightArmorBenchMenu(pContainerId, pPlayerInventory, this); } @Override protected void saveAdditional(CompoundTag pTag) { pTag.put("inventory", itemHandler.serializeNBT()); super.saveAdditional(pTag); } @Override public void load(CompoundTag pTag) { super.load(pTag); itemHandler.deserializeNBT(pTag.getCompound("inventory")); } public void tick(Level pLevel, BlockPos pPos, BlockState pState) { } }   Here is the console output: https://pastebin.com/krgExnYT
    • I couldn't find much usage, I found this and attempted to implement it. It doesn't seem to do anything though. I have this linked to a server to client packet... I have been at this since September seventh and have not made any progress. Blockpos and Blockstate are all pre-assigned variables, as is pLevel. I took the vertex consumer directly from LevelRenderer where I got this code from anyways. I didn't know what number to put into the ModelBakery.DESTROY_TYPES.get() so I just put the breakTime I used in the above code. Am I missing something?
    • Problematic part: [net.minecraft.server.network.ServerGamePacketListenerImpl/]: Gu57 lost connection: Internal Exception: io.netty.handler.codec.EncoderException: java.lang.NullPointerException: Cannot invoke "net.minecraft.resources.ResourceLocation.toString()" because "p_130086_" is null There is no crash, single player works, sadly it's not Hexerei Debug log: (can't use pastebin, cause 10 mb) https://drive.google.com/file/d/16ikQIx7nYjJtF4aJLy5KqFQHh6-jBNrd/view?usp=sharing
    • Something in the Alex's Caves mod is preventing Distant Horizons from rendering. However, I don't want to get rid of Alex's Caves, as it is a part of my personal modded experience. Can someone please find the issue for me?
  • Topics

×
×
  • Create New...

Important Information

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