Перезарядка оружия

При перезарядке патроны пополняют всё оружие в инвентаре ,как сделать так чтоб патроны пополняли только то оружие которое у тебя в руке?

public void onUpdate(ItemStack par1ItemStack, World par2World, Entity par3Entity, int par4, boolean par5)
    {
    EntityPlayer player = (EntityPlayer)par3Entity;
    ItemStack is = player.inventory.getCurrentItem();
   

     if (MyKEY.keyPressed ){
     
     if (par1ItemStack.stackTagCompound == null) {
     
      par1ItemStack.stackTagCompound = new NBTTagCompound();
        
         par1ItemStack.stackTagCompound.setInteger("pat", 0);
     } 
     
     
    if (is != null && is.getItem().itemID == BurntOut.Gun.itemID){
    if (player.inventory.hasItem(BurntOut.Mag3.itemID)){
    if(par1ItemStack.getTagCompound().getInteger("pat") < Batt){
    par1ItemStack.getTagCompound().setInteger("pat", Batt);
         player.inventory.consumeInventoryItem(BurntOut.Mag3.itemID);  
    }
     
     
     }
    }
   }
    }
 
EntityPlayer player = (EntityPlayer)par3Entity;
     ItemStack is = player.inventory.getCurrentItem();
Тебе стак в параметрах даётся
[merge_posts_bbcode]Добавлено: 26.03.2015 22:09:34[/merge_posts_bbcode]

Потом зарефакчу код и кину
 
Dovakin написал(а):
EntityPlayer player = (EntityPlayer)par3Entity;
     ItemStack is = player.inventory.getCurrentItem();
Тебе стак в параметрах даётся
[merge_posts_bbcode]Добавлено: 26.03.2015 22:09:34[/merge_posts_bbcode]

Потом зарефакчу код и кину
Я жду...
 
Код:
public class ItemGun extends Item
{
    public ItemGun(int i)
    {
        super(i);
        super.maxStackSize = 1;
        setMaxDamage(7);
        this.setUnlocalizedName("colt");
        this.setCreativeTab(MafiaII.mafiaTabs);
    }
    public void onPlayerStoppedUsing(ItemStack itemstack, World world, EntityPlayer entityplayer, int i)
    {
        boolean flag = entityplayer.capabilities.isCreativeMode;

        if (itemstack.getItemDamage() < getMaxDamage())
        {
            int j = getMaxItemUseDuration(itemstack) - i;
            float f = 1.0F;
            EntityBullet entitybullet = new EntityBullet(world, entityplayer, 8);
            world.playSoundAtEntity(entityplayer, "colt", 1.0F, 1.0F);
            itemstack.damageItem(1, entityplayer);

            if (!world.isRemote)
            {
                world.spawnEntityInWorld(entitybullet);
            }
        }
        else if (itemstack.getItemDamage() >= getMaxDamage() && entityplayer.inventory.hasItem(MafiaII.itemColtAmmo.itemID))
        {
            int k = getMaxItemUseDuration(itemstack) - i;
            float f1 = (float)k / 20F;
            f1 = (f1 * f1 + f1 * 2.0F) / 3F;

            if (f1 >= 1.0F)
            {
                itemstack.setItemDamage(0);
                world.playSoundAtEntity(entityplayer, "reload", 1.0F, 1.0F);
                entityplayer.inventory.consumeInventoryItem(MafiaII.itemColtAmmo.itemID);
            }
        }
        else
        {
            world.playSoundAtEntity(entityplayer, "random.click", 1.0F, 1.0F);
        }
    }

    public ItemStack onFoodEaten(ItemStack itemstack, World world, EntityPlayer entityplayer)
    {
        return itemstack;
    }

    public int getMaxItemUseDuration(ItemStack itemstack)
    {
        return 0x11940;
    }

    public EnumAction getItemUseAction(ItemStack itemstack)
    {
        if (itemstack.getItemDamage() < getMaxDamage())
        {
            return null;
        }
        else
        {
            return EnumAction.block;
        }
    }

    public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer)
    {
        entityplayer.setItemInUse(itemstack, getMaxItemUseDuration(itemstack));
        return itemstack;
    }

    public void registerIcons(IconRegister par1IconRegister)
    {
        super.itemIcon = par1IconRegister.registerIcon("mafia:colt");
    }
}
 
Код:
world.playSoundAtEntity(entityplayer, "random.click", 1.0F, 1.0F);

Это просто под 1.6.4. или это какой-то вид добавления звука?
 
Можно поставить кастомный звук

Код:
world.playSoundAtEntity(player, "ballistikmod:pistol", 0.5F, 1.0F);
ballistikmod - папка мода
pistol - pistol.ogg файл в папке sound
0.5F - громкость
1.0F - тональность
 
Dovakin написал(а):
Код:
public class ItemGun extends Item
{
    public ItemGun(int i)
    {
        super(i);
        super.maxStackSize = 1;
        setMaxDamage(7);
        this.setUnlocalizedName("colt");
        this.setCreativeTab(MafiaII.mafiaTabs);
    }
    public void onPlayerStoppedUsing(ItemStack itemstack, World world, EntityPlayer entityplayer, int i)
    {
        boolean flag = entityplayer.capabilities.isCreativeMode;

        if (itemstack.getItemDamage() < getMaxDamage())
        {
            int j = getMaxItemUseDuration(itemstack) - i;
            float f = 1.0F;
            EntityBullet entitybullet = new EntityBullet(world, entityplayer, 8);
            world.playSoundAtEntity(entityplayer, "colt", 1.0F, 1.0F);
            itemstack.damageItem(1, entityplayer);

            if (!world.isRemote)
            {
                world.spawnEntityInWorld(entitybullet);
            }
        }
        else if (itemstack.getItemDamage() >= getMaxDamage() && entityplayer.inventory.hasItem(MafiaII.itemColtAmmo.itemID))
        {
            int k = getMaxItemUseDuration(itemstack) - i;
            float f1 = (float)k / 20F;
            f1 = (f1 * f1 + f1 * 2.0F) / 3F;

            if (f1 >= 1.0F)
            {
                itemstack.setItemDamage(0);
                world.playSoundAtEntity(entityplayer, "reload", 1.0F, 1.0F);
                entityplayer.inventory.consumeInventoryItem(MafiaII.itemColtAmmo.itemID);
            }
        }
        else
        {
            world.playSoundAtEntity(entityplayer, "random.click", 1.0F, 1.0F);
        }
    }

    public ItemStack onFoodEaten(ItemStack itemstack, World world, EntityPlayer entityplayer)
    {
        return itemstack;
    }

    public int getMaxItemUseDuration(ItemStack itemstack)
    {
        return 0x11940;
    }

    public EnumAction getItemUseAction(ItemStack itemstack)
    {
        if (itemstack.getItemDamage() < getMaxDamage())
        {
            return null;
        }
        else
        {
            return EnumAction.block;
        }
    }

    public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer)
    {
        entityplayer.setItemInUse(itemstack, getMaxItemUseDuration(itemstack));
        return itemstack;
    }

    public void registerIcons(IconRegister par1IconRegister)
    {
        super.itemIcon = par1IconRegister.registerIcon("mafia:colt");
    }
}
Это мне не очень помогло.
 
Почему? Все тоже,что и у тебя,только хранится в дамаге(он тоже в нбт)
 
Dovakin написал(а):
Почему? Все тоже,что и у тебя,только хранится в дамаге(он тоже в нбт)
Как то не удобно делать через дамаг и перезарядка мне нужна при нажатии клавиши.
 
Делай в TickEvent
[merge_posts_bbcode]Добавлено: 28.03.2015 18:24:12[/merge_posts_bbcode]

Делай в TickEvent
 
Могу показать примерную версию как должно выглядит. (У каждого по своему и я не хочу накручивать свой стиль или типа того.)

Сокращённая версия:
В клиент прокси, в преИнит:
Код:
RegKey.preInit();
В клиент прокси, в инит:
Код:
FMLCommonHandler.instance().bus().register(new EventActionPrimaryKey());
RegKey
Код:
public class RegKey {

    private static final String cat_name = "category.control_button.name";

    public static final KeyBinding reload = new KeyBinding("key.reload.name", Keyboard.KEY_R, cat_name);
    
    public static void preInit() {

        ClientRegistry.registerKeyBinding(reload);

    }

}

EventActionPrimaryKey
Код:
public class EventActionPrimaryKey {

    boolean k_reload, k_reload_last = false;

    @SubscribeEvent
    public void actionReload(TickEvent.PlayerTickEvent event) {
        if (event.phase == TickEvent.Phase.START && event.side == Side.CLIENT) {
            if (RegKey.reload.getIsKeyPressed()) {
                k_reload = true;
                if (!k_reload_last && k_reload) ActionPrimaryKey.actionReloadClient(event.player, true);//press down
                k_reload_last = k_reload;
            } else {
                k_reload = false;
                if (k_reload_last && !k_reload) ActionPrimaryKey.actionReloadClient(event.player, false);//unpress down
                k_reload_last = k_reload;
            }
        }
    }

}

ActionPrimaryKey
Код:
public class ActionPrimaryKey {
    
    public static void actionReloadClient(EntityPlayer player, boolean buttonstate) {
        ItemStack current = player.getCurrentEquippedItem();
        if (current != null && current.getItem() instanceof IActionPrimaryKey)
            ((IActionPrimaryKey)current.getItem()).onReloadClient(current, player.worldObj, player, buttonstate);
    }
    
}

IActionPrimaryKey
Код:
public interface IActionPrimaryKey {

    @SideOnly(Side.CLIENT)
    public void onReloadClient(ItemStack is, World world, EntityPlayer player, boolean isPress);

}

В нашем предмете, после:
Код:
extends Item
Добавляем:
Код:
implements IActionPrimaryKey
Затем он попросит добавить:

Код:
    @SideOnly(Side.CLIENT)
    public void onReloadClient(ItemStack is, World world, EntityPlayer player, boolean isPress) {

    }

Пока-что у нас получилось создать метод, который будет работать на клиенте, по-этому нужно использовать пакеты, чтобы заработало на сервере.

В главном классе мода, добавить перед методами:
Код:
public static SimpleNetworkWrapper network;

В преИните добавить:
Код:
network = NetworkRegistry.INSTANCE.newSimpleChannel(PackWeapons.MODID);
network.registerMessage(MessageActionWeapons.Handler.class, MessageActionWeapons.class, 0, Side.SERVER);

MessageActionWeapons
Код:
public class MessageActionWeapons implements IMessage {

    public int button;

    public MessageActionWeapons() {}

    public MessageActionWeapons(int button) {
        this.button = button;
    }

    @Override
    public void toBytes(ByteBuf buf) {
        buf.writeInt(button);
    }

    @Override
    public void fromBytes(ByteBuf buf) {
        button = buf.readInt();
    }
    //----------------------------------------------------------------------------------
    public static class Handler implements IMessageHandler<MessageActionWeapons, IMessage> {

        @Override
        public IMessage onMessage(MessageActionWeapons packet, MessageContext message) {
            int button = packet.button;
            EntityPlayerMP player = message.getServerHandler().playerEntity;

            switch(button) {
            //case 1:ActionWeapons.onFire(player);break;
            case 3:ActionWeapons.onReload(player);break;
            }

            return null;
        }

    }
    //----------------------------------------------------------------------------------
}

ActionWeapons
Код:
public class ActionWeapons {

    public static void onReload(EntityPlayer player) {
        ItemStack current = player.getCurrentEquippedItem();
        if (current != null && current.getItem() instanceof ItemWeapons)
            ((ItemWeapons)current.getItem()).reload(current, player.worldObj, player);
    }

}
ItemWeapons - это наш итем.

В нашем итеме добавляем метод:
Код:
    public void reload(ItemStack is, World world, EntityPlayer player) {
    //Тут добавляешь условия для перезарядки и саму перезарядку.
    }


Код:
    @SideOnly(Side.CLIENT)
    public void onReloadClient(ItemStack is, World world, EntityPlayer player, boolean isPress) {
        if (isPress) PackWeapons.network.sendToServer(new MessageActionWeapons(3));
    }
PackWeapons - это главный класс мода.

У меня примерно так выглядит:
Код:
    @SideOnly(Side.CLIENT)
    public void onReloadClient(ItemStack is, World world, EntityPlayer player, boolean isPress) {
        if (isPress) PackWeapons.network.sendToServer(new MessageActionWeapons(3));
    }

    public void reload(ItemStack is, World world, EntityPlayer player) {
        NBTTagCompound nbt = is.getTagCompound();
        if (nbt != null && nbt.hasKey("Weapon")) {
            world.playSoundAtEntity(player, WeaponFor.get(nbt.getString("Weapon")).getSoundReload()[0], 1.0F, 1.0F);
            if (Core.show_system_info_testing) System.out.println("-reload-");
            nbt.setInteger("AmmoAtm", WeaponFor.get(nbt.getString("Weapon")).getSizeAmmo());
            is.setTagCompound(nbt);
        }
    }
"AmmoAtm" - количество патронов в оружии.

Ну как-то так. Я показал сокращённую версию (у меня по-больше кнопок и по больше методов, а оружие до-сих пор разрабатывается [так как не особо с оружием занимаюсь]).
 
timaxa007 написал(а):
Могу показать примерную версию как должно выглядит. (У каждого по своему и я не хочу накручивать свой стиль или типа того.)

Сокращённая версия:
В клиент прокси, в преИнит:
Код:
RegKey.preInit();
В клиент прокси, в инит:
Код:
FMLCommonHandler.instance().bus().register(new EventActionPrimaryKey());
RegKey
Код:
public class RegKey {

    private static final String cat_name = "category.control_button.name";

    public static final KeyBinding reload = new KeyBinding("key.reload.name", Keyboard.KEY_R, cat_name);
    
    public static void preInit() {

        ClientRegistry.registerKeyBinding(reload);

    }

}

EventActionPrimaryKey
Код:
public class EventActionPrimaryKey {

    boolean k_reload, k_reload_last = false;

    @SubscribeEvent
    public void actionReload(TickEvent.PlayerTickEvent event) {
        if (event.phase == TickEvent.Phase.START && event.side == Side.CLIENT) {
            if (RegKey.reload.getIsKeyPressed()) {
                k_reload = true;
                if (!k_reload_last && k_reload) ActionPrimaryKey.actionReloadClient(event.player, true);//press down
                k_reload_last = k_reload;
            } else {
                k_reload = false;
                if (k_reload_last && !k_reload) ActionPrimaryKey.actionReloadClient(event.player, false);//unpress down
                k_reload_last = k_reload;
            }
        }
    }

}

ActionPrimaryKey
Код:
public class ActionPrimaryKey {
    
    public static void actionReloadClient(EntityPlayer player, boolean buttonstate) {
        ItemStack current = player.getCurrentEquippedItem();
        if (current != null && current.getItem() instanceof IActionPrimaryKey)
            ((IActionPrimaryKey)current.getItem()).onReloadClient(current, player.worldObj, player, buttonstate);
    }
    
}

IActionPrimaryKey
Код:
public interface IActionPrimaryKey {

    @SideOnly(Side.CLIENT)
    public void onReloadClient(ItemStack is, World world, EntityPlayer player, boolean isPress);

}

В нашем предмете, после:
Код:
extends Item
Добавляем:
Код:
implements IActionPrimaryKey
Затем он попросит добавить:

Код:
    @SideOnly(Side.CLIENT)
    public void onReloadClient(ItemStack is, World world, EntityPlayer player, boolean isPress) {

    }

Пока-что у нас получилось создать метод, который будет работать на клиенте, по-этому нужно использовать пакеты, чтобы заработало на сервере.

В главном классе мода, добавить перед методами:
Код:
public static SimpleNetworkWrapper network;

В преИните добавить:
Код:
network = NetworkRegistry.INSTANCE.newSimpleChannel(PackWeapons.MODID);
network.registerMessage(MessageActionWeapons.Handler.class, MessageActionWeapons.class, 0, Side.SERVER);

MessageActionWeapons
Код:
public class MessageActionWeapons implements IMessage {

    public int button;

    public MessageActionWeapons() {}

    public MessageActionWeapons(int button) {
        this.button = button;
    }

    @Override
    public void toBytes(ByteBuf buf) {
        buf.writeInt(button);
    }

    @Override
    public void fromBytes(ByteBuf buf) {
        button = buf.readInt();
    }
    //----------------------------------------------------------------------------------
    public static class Handler implements IMessageHandler<MessageActionWeapons, IMessage> {

        @Override
        public IMessage onMessage(MessageActionWeapons packet, MessageContext message) {
            int button = packet.button;
            EntityPlayerMP player = message.getServerHandler().playerEntity;

            switch(button) {
            //case 1:ActionWeapons.onFire(player);break;
            case 3:ActionWeapons.onReload(player);break;
            }

            return null;
        }

    }
    //----------------------------------------------------------------------------------
}

ActionWeapons
Код:
public class ActionWeapons {

    public static void onReload(EntityPlayer player) {
        ItemStack current = player.getCurrentEquippedItem();
        if (current != null && current.getItem() instanceof ItemWeapons)
            ((ItemWeapons)current.getItem()).reload(current, player.worldObj, player);
    }

}
ItemWeapons - это наш итем.

В нашем итеме добавляем метод:
Код:
    public void reload(ItemStack is, World world, EntityPlayer player) {
    //Тут добавляешь условия для перезарядки и саму перезарядку.
    }


Код:
    @SideOnly(Side.CLIENT)
    public void onReloadClient(ItemStack is, World world, EntityPlayer player, boolean isPress) {
        if (isPress) PackWeapons.network.sendToServer(new MessageActionWeapons(3));
    }
PackWeapons - это главный класс мода.

У меня примерно так выглядит:
Код:
    @SideOnly(Side.CLIENT)
    public void onReloadClient(ItemStack is, World world, EntityPlayer player, boolean isPress) {
        if (isPress) PackWeapons.network.sendToServer(new MessageActionWeapons(3));
    }

    public void reload(ItemStack is, World world, EntityPlayer player) {
        NBTTagCompound nbt = is.getTagCompound();
        if (nbt != null && nbt.hasKey("Weapon")) {
            world.playSoundAtEntity(player, WeaponFor.get(nbt.getString("Weapon")).getSoundReload()[0], 1.0F, 1.0F);
            if (Core.show_system_info_testing) System.out.println("-reload-");
            nbt.setInteger("AmmoAtm", WeaponFor.get(nbt.getString("Weapon")).getSizeAmmo());
            is.setTagCompound(nbt);
        }
    }
"AmmoAtm" - количество патронов в оружии.

Ну как-то так. Я показал сокращённую версию (у меня по-больше кнопок и по больше методов, а оружие до-сих пор разрабатывается [так как не особо с оружием занимаюсь]).
Какая версия ?
 
Назад
Сверху