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

59 lines
1.9 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.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 onUseOnItem(player: ServerPlayerEntity, playerInv: PlayerInventory, heldStackBeforeUse: ItemStack) {
val heldStack = playerInv.mainHandStack
if (!player.isCreative && heldStack.isEmpty) {
val index = playerInv.main.indexOfFirst {
ItemStack.areItemsEqualIgnoreDamage(heldStackBeforeUse, it)
}
if (index >= 0) {
playerInv.swapSlotWithHotbar(index)
val newStack = playerInv.mainHandStack
player.networkHandler.sendPacket(EntityEquipmentUpdateS2CPacket(player.entityId, EquipmentSlot.MAINHAND, 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)
}
}
}
}