AutoSwap/src/main/kotlin/net/shadowfacts/autoswap/AutoSwap.kt

64 lines
2.0 KiB
Kotlin

package net.shadowfacts.autoswap
import net.fabricmc.api.ModInitializer
import net.minecraft.client.network.packet.EntityEquipmentUpdateS2CPacket
import net.minecraft.client.network.packet.ItemPickupAnimationS2CPacket
import net.minecraft.entity.EquipmentSlot
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.entity.player.PlayerInventory
import net.minecraft.item.ItemStack
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.util.Hand
import net.minecraft.util.math.BlockPos
/**
* @author shadowfacts
*/
object AutoSwap: ModInitializer {
override fun onInitialize() {
}
fun endBreakBlock(playerInv: PlayerInventory, heldStackAtBeginningOfBreak: ItemStack) {
val currentlySelected = playerInv.mainHandStack
if (currentlySelected.isEmpty && !heldStackAtBeginningOfBreak.isEmpty) {
val index = playerInv.main.indexOfFirst {
ItemStack.areItemsEqualIgnoreDamage(heldStackAtBeginningOfBreak, it)
}
if (index >= 0) {
playerInv.swapSlotWithHotbar(index)
}
}
}
fun afterUseOnBlock(player: ServerPlayerEntity, playerInv: PlayerInventory, heldStackBeforeUse: ItemStack, hand: Hand) {
val heldStack = player.getStackInHand(hand)
if (!player.isCreative && heldStack.isEmpty) {
val index = playerInv.main.indexOfFirst {
ItemStack.areItemsEqualIgnoreDamage(heldStackBeforeUse, it)
}
if (index >= 0) {
val newStack = playerInv.removeInvStack(index)
player.setStackInHand(hand, newStack)
val slot = when (hand) {
Hand.MAIN_HAND -> EquipmentSlot.MAINHAND
Hand.OFF_HAND -> EquipmentSlot.OFFHAND
}
player.networkHandler.sendPacket(EntityEquipmentUpdateS2CPacket(player.entityId, slot, newStack))
}
}
}
fun afterAttack(playerInv: PlayerInventory, heldStackBeforeAttack: ItemStack) {
val heldStack = playerInv.mainHandStack
if (!heldStackBeforeAttack.isEmpty && heldStack.isEmpty) {
val index = playerInv.main.indexOfFirst {
ItemStack.areItemsEqualIgnoreDamage(heldStackBeforeAttack, it)
}
if (index >= 0) {
playerInv.swapSlotWithHotbar(index)
}
}
}
}