• Minecraft 1.18.1、1.18.2模组开发 22.狙击枪(Sniper Rifle)


    Minecraft 1.18.1、1.18.2模组开发 05.发射器+投掷物

    我们今天在模组中实现一把狙击枪。

    1.与第5期教程类似,我们需要首先制作枪械的模型和子弹的模型:

    cr1.png

    不过我们本次希望狙击枪在副手时就进入开镜状态,所以我们要专门设置一个副手形态的狙击枪的第一人称视野。

    cr2.png

    之后导出为.json文件,将导出的.json文件放入resources\assets\你的模组名称\models\item中:

    cr3.png

    2.在Items包中新建一个我们子弹的物品类ItemSniperAmmo:

    ItemSniperAmmo

    package com.joy187.re8joymod.items;
    
    import com.joy187.re8joymod.Main;
    import com.joy187.re8joymod.entity.EntitySniperAmmo;
    
    import net.minecraft.world.entity.LivingEntity;
    import net.minecraft.world.item.Item;
    import net.minecraft.world.item.ItemStack;
    import net.minecraft.world.item.Item.Properties;
    import net.minecraft.world.level.Level;
    
    public class ItemSniperAmmo extends Item {
        public ItemSniperAmmo() {
            super(new Properties().tab(Main.TUTORIAL_TAB).stacksTo(16));
        }
    
        public EntitySniperAmmo createArrow(Level p_200887_1_, ItemStack p_200887_2_, LivingEntity p_200887_3_) {
            EntitySniperAmmo arrowentity = new EntitySniperAmmo(p_200887_1_, p_200887_3_);
            return arrowentity;
        }
    
    
        public boolean isInfinite(ItemStack stack, ItemStack bow, net.minecraft.world.entity.player.Player player) {
            int enchant = net.minecraft.world.item.enchantment.EnchantmentHelper.getItemEnchantmentLevel(net.minecraft.world.item.enchantment.Enchantments.INFINITY_ARROWS, bow);
            return enchant <= 0 ? false : this.getClass() == ItemSniperAmmo.class;
         }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    在Init包的ItemInit类中添加我们的投掷物物品声明:

    ItemInit.java

    public class ItemInit {
        public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS,
                Main.MOD_ID);
    
        //我们的投掷物品声明
        public static RegistryObject<Item> SNIPERAMMO = ITEMS.register("sniperammo",()->
        {
            return new ItemSniperAmmo();
        });
    
        private static <T extends Item> RegistryObject<T> register(final String name, final Supplier<T> item) {
            return ITEMS.register(name, item);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    3.在entity包中新建我们的子弹实体类EntitySniperAmmo

    EntitySniperAmmo.java

    package com.joy187.re8joymod.entity;
    
    import com.joy187.re8joymod.init.EntityInit;
    import com.joy187.re8joymod.init.ItemInit;
    
    import io.netty.buffer.Unpooled;
    import net.minecraft.network.FriendlyByteBuf;
    import net.minecraft.network.protocol.Packet;
    import net.minecraft.network.syncher.EntityDataAccessor;
    import net.minecraft.network.syncher.EntityDataSerializers;
    import net.minecraft.network.syncher.SynchedEntityData;
    import net.minecraft.world.damagesource.DamageSource;
    import net.minecraft.world.entity.Entity;
    import net.minecraft.world.entity.EntityType;
    import net.minecraft.world.entity.LivingEntity;
    import net.minecraft.world.entity.monster.AbstractSkeleton;
    import net.minecraft.world.entity.monster.Blaze;
    import net.minecraft.world.entity.monster.Ravager;
    import net.minecraft.world.entity.projectile.ThrowableItemProjectile;
    import net.minecraft.world.item.Item;
    import net.minecraft.world.level.Level;
    import net.minecraft.world.phys.EntityHitResult;
    import net.minecraftforge.network.NetworkHooks;
    
    
    public class EntitySniperAmmo extends ThrowableItemProjectile{
        
    	public int explosionPower = 1,id=91082;
        public double damage;
        private int ticksInGround;
        private static final EntityDataAccessor<Integer> ID_EFFECT_COLOR = SynchedEntityData.defineId(EntitySniperAmmo.class, EntityDataSerializers.INT);
    
    	
    	public EntitySniperAmmo(EntityType<?> entityIn, Level level) {
    		super((EntityType<? extends EntitySniperAmmo>) entityIn, level);
            //this.size(1.0F, 1.0F);
            this.damage = 24D;
    		// TODO Auto-generated constructor stub
    	}
    	
    	public EntitySniperAmmo(Level world, LivingEntity entity) {
    	    super(EntityInit.SNIPERAMMO.get(), entity, world);
    	    this.damage= 24D;
    	}
    	
    	//我们的子弹与之前的物品绑定
    	@Override
    	protected Item getDefaultItem() {
    		return ItemInit.SNIPERAMMO.get();
    	}
    	   
    	//当物体打击到实体上造成的伤害
        protected void onHitEntity(EntityHitResult result) {
            super.onHitEntity(result);
            Entity entity = result.getEntity();
    
    
            int i = 24;
            if(entity instanceof Blaze || entity instanceof Ravager){
                i = 28;
            }
            if(entity instanceof EntityBei || entity instanceof EntityHeisen){
                i= 35;
            }
            if(entity instanceof EntityUrias || entity instanceof EntityUriass){
                i= 25;
            }
            if(entity instanceof EntityLycana || entity instanceof AbstractSkeleton){
                i= 45;
            }
            entity.hurt(DamageSource.thrown(this, this.getOwner()), (float)(i+random.nextFloat()*0.5*this.damage));
    
        }
        
        
        protected void onHit(EntityHitResult p_70227_1_) {
            super.onHit(p_70227_1_);
            if (!this.level.isClientSide) {
                this.level.broadcastEntityEvent(this, (byte)3);
                this.remove(Entity.RemovalReason.KILLED);
            }
        }
        
        @Override
        public Packet<?> getAddEntityPacket() {
        	FriendlyByteBuf pack = new FriendlyByteBuf(Unpooled.buffer());
            pack.writeDouble(getX());
            pack.writeDouble(getY());
            pack.writeDouble(getZ());
            pack.writeInt(getId());
            pack.writeUUID(getUUID());
    
            return NetworkHooks.getEntitySpawningPacket(this);
    
        }
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97

    4.为我们的投掷物进行渲染,render包中新建一个渲染类RenderSniperAmmo

    RenderSniperAmmo.java

    package com.joy187.re8joymod.entity.render;
    
    import com.joy187.re8joymod.Main;
    import com.joy187.re8joymod.entity.EntitySniperAmmo;
    import com.mojang.blaze3d.vertex.PoseStack;
    import com.mojang.blaze3d.vertex.VertexConsumer;
    import com.mojang.math.Matrix3f;
    import com.mojang.math.Matrix4f;
    import com.mojang.math.Vector3f;
    
    import net.minecraft.client.renderer.MultiBufferSource;
    import net.minecraft.client.renderer.RenderType;
    import net.minecraft.client.renderer.block.model.ItemTransforms;
    import net.minecraft.client.renderer.entity.EntityRenderer;
    import net.minecraft.client.renderer.entity.EntityRendererProvider;
    import net.minecraft.client.renderer.entity.ItemRenderer;
    import net.minecraft.client.renderer.texture.OverlayTexture;
    import net.minecraft.core.BlockPos;
    import net.minecraft.resources.ResourceLocation;
    
    
    public class RenderSniperAmmo extends EntityRenderer<EntitySniperAmmo> {
    
        //你的子弹的贴图位置
    	public static final ResourceLocation TEXTURE = new ResourceLocation(Main.MOD_ID ,"textures/item/zhihu.png");
    	private static final float MIN_CAMERA_DISTANCE_SQUARED = 12.25F;
    	private final ItemRenderer itemRenderer;
    	   private final float scale;
    	   private final boolean fullBright;
    	   
        public RenderSniperAmmo(EntityRendererProvider.Context manager) {
            //this.itemRenderer = manager.getItemRenderer();
            super(manager);
            this.itemRenderer=manager.getItemRenderer();
            this.scale=0.25F;
            this.fullBright=false;
    
         }
        
    
        private static final RenderType field_229044_e_ = RenderType.entityCutoutNoCull(TEXTURE);
    
    
        protected int getSkyLightLevel(EntitySniperAmmo p_239381_1_, BlockPos p_239381_2_) {
            return 1;
        }
        @Override
        public ResourceLocation getTextureLocation(EntitySniperAmmo p_110775_1_) {
            return TEXTURE;
        }
        
        public void render(EntitySniperAmmo entityIn, float entityYaw, float partialTicks, PoseStack poseStackIn, MultiBufferSource bufferIn, int packedLightIn) {
            if (entityIn.tickCount >= 2 || !(this.entityRenderDispatcher.camera.getEntity().distanceToSqr(entityIn) < 12.25D)) {
               poseStackIn.pushPose();
               poseStackIn.scale(this.scale, this.scale, this.scale);
               poseStackIn.mulPose(this.entityRenderDispatcher.cameraOrientation());
               poseStackIn.mulPose(Vector3f.YP.rotationDegrees(180.0F));
               this.itemRenderer.renderStatic(entityIn.getItem(), ItemTransforms.TransformType.GROUND, packedLightIn, OverlayTexture.NO_OVERLAY, poseStackIn, bufferIn, entityIn.getId());
               poseStackIn.popPose();
               super.render(entityIn, entityYaw, partialTicks, poseStackIn, bufferIn, packedLightIn);
               
            }
         }
        
        private static void vertexRender(VertexConsumer p_229045_0_, Matrix4f p_229045_1_, Matrix3f p_229045_2_, int p_229045_3_, float p_229045_4_, int p_229045_5_, int p_229045_6_, int p_229045_7_) {
            p_229045_0_.vertex(p_229045_1_, p_229045_4_ - 0.5F, (float)p_229045_5_ - 0.25F, 0.0F).color(255, 255, 255, 255).overlayCoords(OverlayTexture.NO_OVERLAY).normal(p_229045_2_, 0.0F, 1.0F, 0.0F).endVertex();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

    ClientModEventSubscriber.java中添加我们的投掷物的渲染事件注册:

    ClientModEventSubscriber.java

    package com.joy187.re8joymod;
    
    import net.minecraftforge.fml.common.Mod;
    import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
    import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
    
    import com.joy187.re8joymod.entity.EntityRe8Dimi;
    import com.joy187.re8joymod.entity.model.ModelRe8Dimi;
    import com.joy187.re8joymod.entity.render.RenderMoSpitter;
    import com.joy187.re8joymod.entity.render.RenderRe8Dimi;
    import com.joy187.re8joymod.init.EntityInit;
    
    import net.minecraft.client.Minecraft;
    import net.minecraft.client.renderer.entity.EntityRendererProvider;
    import net.minecraft.client.renderer.entity.ThrownItemRenderer;
    import net.minecraft.world.entity.Entity;
    import net.minecraft.world.entity.EntityType;
    import net.minecraftforge.api.distmarker.Dist;
    import net.minecraftforge.client.event.EntityRenderersEvent;
    import net.minecraftforge.event.entity.EntityAttributeCreationEvent;
    import net.minecraftforge.eventbus.api.SubscribeEvent;
    
    @Mod.EventBusSubscriber(modid = Main.MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
    public class ClientModEventSubscriber
    {
    
        @SubscribeEvent
        public static void onRegisterLayers(EntityRenderersEvent.RegisterLayerDefinitions event) {
            event.registerLayerDefinition(ModelRe8Dimi.LAYER_LOCATION, ModelRe8Dimi::createBodyLayer);
        }
    
        @SubscribeEvent
        public static void onRegisterRenderer(EntityRenderersEvent.RegisterRenderers event) {
            event.registerEntityRenderer(EntityInit.RE8DIMI.get(), RenderRe8Dimi::new);
    
            //添加我们的投掷物的渲染事件
            event.registerEntityRenderer(EntityInit.SNIPERAMMO.get(), RenderSniperAmmo::new);
    
        }
    
        @SubscribeEvent
        public static void onAttributeCreate(EntityAttributeCreationEvent event) {
            event.put(EntityInit.RE8DIMI.get(), EntityRe8Dimi.prepareAttributes().build());
        }
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    5.子弹制作完成,来到枪械部分。在Item中新建我们狙击枪类ItemF2

    ItemF2.java

    package com.joy187.re8joymod.items;
    
    import java.util.List;
    import java.util.function.Predicate;
    
    import javax.annotation.Nullable;
    
    import com.joy187.re8joymod.ClientModEventSubscriber;
    import com.joy187.re8joymod.Main;
    import com.joy187.re8joymod.entity.EntitySniperAmmo;
    import com.joy187.re8joymod.init.ItemInit;
    import com.joy187.re8joymod.init.SoundInit;
    
    import net.minecraft.ChatFormatting;
    import net.minecraft.client.Minecraft;
    import net.minecraft.core.particles.ParticleTypes;
    import net.minecraft.network.chat.Component;
    import net.minecraft.network.chat.TextComponent;
    import net.minecraft.sounds.SoundSource;
    import net.minecraft.stats.Stats;
    import net.minecraft.world.InteractionHand;
    import net.minecraft.world.InteractionResultHolder;
    import net.minecraft.world.entity.Entity;
    import net.minecraft.world.entity.LivingEntity;
    import net.minecraft.world.entity.player.Player;
    import net.minecraft.world.item.Item;
    import net.minecraft.world.item.ItemStack;
    import net.minecraft.world.item.ProjectileWeaponItem;
    import net.minecraft.world.item.TooltipFlag;
    import net.minecraft.world.item.Vanishable;
    import net.minecraft.world.item.enchantment.EnchantmentHelper;
    import net.minecraft.world.item.enchantment.Enchantments;
    import net.minecraft.world.level.Level;
    
    
    public class ItemF2 extends ProjectileWeaponItem implements Vanishable {
    
        public ItemF2() {
            super(new ItemF2.Properties().tab(Main.TUTORIAL_TAB).stacksTo(1));
        }
        
    	public ItemF2(Item.Properties name) {
    		  super(name);
    	}
    
        public void releaseUsing(ItemStack p_77615_1_, Level level, LivingEntity p_77615_3_, int p_77615_4_) {
            if (p_77615_3_ instanceof Player) {
                Player Player = (Player)p_77615_3_;
                //OneHandedPose.renderFirstPersonArms(Player, Player.HAND_SLOTS, p_77615_1_, Player.getPose(), Player.buffer, p_77615_4_, p_77615_4_);
                
                boolean flag = Player.getAbilities().instabuild || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.INFINITY_ARROWS, p_77615_1_) > 0;
    //            ItemStack itemstack = Player.getProjectile(p_77615_1_);
    
                ItemStack itemstack = this.findAmmo(Player);
    
                int i = this.getUseDuration(p_77615_1_) - p_77615_4_;
                i = net.minecraftforge.event.ForgeEventFactory.onArrowLoose(p_77615_1_, level, Player, i, !itemstack.isEmpty() || flag);
                if (i < 0) return;
    
                if (!itemstack.isEmpty() || flag) {
                    if (itemstack.isEmpty()) {
                        itemstack = new ItemStack(ItemInit.SNIPERAMMO.get().asItem());
                    }
    
                    float f = getPowerForTime(i);
                    if (!((double)f < 0.1D)) {
                        boolean flag1 = Player.getAbilities().instabuild || (itemstack.getItem() instanceof ItemSniperAmmo && ((ItemSniperAmmo)itemstack.getItem()).isInfinite(itemstack, p_77615_1_, Player));
                        if (!level.isClientSide) {
                            ItemSniperAmmo arrowitem = (ItemSniperAmmo)(itemstack.getItem() instanceof ItemSniperAmmo ? itemstack.getItem() : ItemInit.SNIPERAMMO.get().asItem());
                            EntitySniperAmmo abstractarrowentity = arrowitem.createArrow(level, itemstack, Player);
    
                            abstractarrowentity = customArrow(abstractarrowentity);
                            //abstractarrowentity.setItem(itemstack);
                            abstractarrowentity.shootFromRotation(Player, Player.getXRot(), Player.getYRot(), 0.2F, f * 30.0F, 0.75F);
    
                            abstractarrowentity.level.addParticle(ParticleTypes.FLAME, abstractarrowentity.getX(), abstractarrowentity.getY(), abstractarrowentity.getZ(), abstractarrowentity.position().x , abstractarrowentity.position().y, abstractarrowentity.position().z);
                            abstractarrowentity.playSound(SoundInit.R2FIRE.get(), 4.5F,4.5F);
    
    
                            if (EnchantmentHelper.getItemEnchantmentLevel(Enchantments.FLAMING_ARROWS, p_77615_1_) > 0) {
                                abstractarrowentity.setSecondsOnFire(100);
                            }
    
                            p_77615_1_.hurtAndBreak(1, Player, (p_220009_1_) -> {
                                p_220009_1_.broadcastBreakEvent(Player.getUsedItemHand());
                            });
    
    
                            abstractarrowentity.level.addParticle(ParticleTypes.FLAME, abstractarrowentity.getX(), abstractarrowentity.getY(), abstractarrowentity.getZ(), abstractarrowentity.position().x * -0.2D, 0.08D, abstractarrowentity.position().z * -0.2D);
    
                            level.addFreshEntity(abstractarrowentity);
                        }
                        
                        //发射的声音
                        level.playSound((Player)null, Player.getX(), Player.getY(), Player.getZ(), SoundInit.R2FIRE.get(), SoundSource.PLAYERS, 4.5F, 4.5F / (Player.getRandom().nextFloat() * 0.2F + 1.2F) + f * 0.5F);
                        if (!flag1 && !Player.getAbilities().instabuild) {
                            itemstack.shrink(1);
                            if (itemstack.isEmpty()) {
                                Player.getInventory().removeItem(itemstack);
                            }
                        }
                        
                        //每次发射成功后就间隔1.5s再发射(30=20*1.5)
                        Player.getCooldowns().addCooldown(this, 30);
    
                        Player.awardStat(Stats.ITEM_USED.get(this));
                    }
                }
            }
        }
    
        public InteractionResultHolder<ItemStack> use(Level level, Player palyerIn, InteractionHand handIn) {
            ItemStack itemstack = palyerIn.getItemInHand(handIn);
            boolean flag = !this.findAmmo(palyerIn).isEmpty();
    
            InteractionResultHolder<ItemStack> ret = net.minecraftforge.event.ForgeEventFactory.onArrowNock(itemstack, level, palyerIn, handIn, flag);
            if (ret != null) return ret;
    
            if (!palyerIn.getAbilities().instabuild && !flag) {
                return InteractionResultHolder.fail(itemstack);
            } else {
                palyerIn.startUsingItem(handIn);
                return InteractionResultHolder.consume(itemstack);
            }
        }
    
        public static float getPowerForTime(int p_185059_0_) {
            float f = (float)p_185059_0_ / 20.0F;
            f = (f * f + f * 2.0F) / 3.0F;
            if (f > 1.0F) {
                f = 1.0F;
            }
    
            return f;
        }
    
    
        public int getUseDuration(ItemStack p_77626_1_) {
            return 500;
        }
    
    
        public Predicate<ItemStack> getAllSupportedProjectiles() {
            return ARROW_OR_FIREWORK;
        }
    
        public  EntitySniperAmmo customArrow(EntitySniperAmmo arrow) {
            return arrow;
        }
        public int getDefaultProjectileRange() {
            return 15;
        }
        
        //判断是否能找到我们的专属子弹
        protected ItemStack findAmmo(Player player)
        {
            if (this.isSniperAmmo(player.getItemInHand(InteractionHand.OFF_HAND)))
            {
                return player.getItemInHand(InteractionHand.OFF_HAND);
            }
            else if (this.isSniperAmmo(player.getItemInHand(InteractionHand.MAIN_HAND)))
            {
                return player.getItemInHand(InteractionHand.MAIN_HAND);
            }
            else
            {
                for (int i = 0; i < player.getInventory().getContainerSize(); ++i)
                {
                    ItemStack itemstack = player.getInventory().getItem(i);
    
                    if (this.isSniperAmmo(itemstack))
                    {
                        return itemstack;
                    }
                }
    
                return ItemStack.EMPTY;
            }
        }
    
        protected boolean isSniperAmmo(ItemStack stack)
        {
            return stack.getItem() instanceof ItemSniperAmmo;
        }
    	
        @Override
        public boolean onEntitySwing(ItemStack stack, LivingEntity entity)
        {
            return true;
        }
    	
        public void initializeClient(java.util.function.Consumer<net.minecraftforge.client.IItemRenderProperties> consumer) {
        
        }
        
        //对枪械的状态进行监视
        public void inventoryTick(ItemStack p_77663_1_, Level p_77663_2_, Entity p_77663_3_, int p_77663_4_, boolean p_77663_5_) {
            if(p_77663_3_ instanceof Player)
            {
                ItemStack item = ((Player)p_77663_3_).getItemInHand(InteractionHand.OFF_HAND);
                
              //如果玩家副手装备了这把枪
              if(item.getItem() == ItemInit.F2RIFLE.get())
              {
                 //让视野变成开镜状态(数值越小放大越大)
            	 Minecraft.getInstance().options.fov=12;
              }
              else {
                 //不在副手就回复视野范围
             	 Minecraft.getInstance().options.fov=70;
              }
            }
    
        }
        
        @Override
        public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) {
        	tooltip.add(Component.nullToEmpty(ChatFormatting.GOLD+"Press 'F' to offhand for scoping."));
        	tooltip.add(Component.nullToEmpty(ChatFormatting.GOLD+"Ammo Type:Sniper Rifle Ammo"));
        }
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222

    ItemInit类中添加我们枪械的声明:

    ItemInit.java

        public static RegistryObject<Item> SA110 = ITEMS.register("sa110",()->
        {
            return new ItemF2();
        });
    
    • 1
    • 2
    • 3
    • 4

    6.我们为自己的枪械设计了专门的声音,在SoundInit中进行注册:

    SoundInit.java

    package com.joy187.re8joymod.init;
    
    import net.minecraftforge.registries.RegistryObject;
    
    import com.joy187.re8joymod.Main;
    
    import net.minecraft.resources.ResourceLocation;
    import net.minecraft.sounds.SoundEvent;
    import net.minecraftforge.registries.DeferredRegister;
    import net.minecraftforge.registries.ForgeRegistries;
    
    public class SoundInit {
    
    
        public static final DeferredRegister<SoundEvent> SOUNDS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, Main.MOD_ID);
        
        //我们的枪械声音
        public static final RegistryObject<SoundEvent> R2FIRE = build("entity.m1851.f2rifle");
    
    
        private static RegistryObject<SoundEvent> build(String id)
        {
            return SOUNDS.register(id, () -> new SoundEvent(new ResourceLocation(Main.MOD_ID, id)));
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    在项目主类的Main函数中将SoundInit类进行注册:

    	public Main() {
    		IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
    
    		ItemInit.ITEMS.register(bus);
    		BlockInit.BLOCKS.register(bus);
    		EntityInit.ENTITY_TYPES.register(bus);
    		EffectInit.EFFECTS.register(bus);
    		PotionInit.POTIONS.register(bus);
    
            //添加这个
    		SoundInit.SOUNDS.register(bus);
    
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    将声音文件转换为.ogg格式,放入src\main\resources\assets\你的modid\sounds\entity\m1851路径下。

    7.代码部分结束,进入资源包制作环节。在resources包中的sounds.json文件中添加我们的枪械声音:

    sounds.json

      "entity.m1851.f2rifle":{
        "category":"entity",
        "subtitle" :"entity.m1851.f2rifle.sub",
        "sounds":[{ "name": "re8joymod:entity/m1851/f2rifle", "stream":true }]
      },
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在lang包中的en_us.json中添加枪械、子弹物品、子弹实体的英文名称:

    en_us.json

      "entity.re8joymod.sniperammo": "Sniper Rifle Ammo",
    
      "item.re8joymod.f2rifle": "F2 Rifle",
      "item.re8joymod.sniperammo": "Sniper Rifle Ammo",
    
    • 1
    • 2
    • 3
    • 4

    在lang包中的zh_cn.json中添加枪械、子弹物品、子弹实体的中文名称:

    zh_cn.json

      "item.re8joymod.sniperammo": "狙击枪子弹",
      "item.re8joymod.f2rifle": "F2 狙击枪",
      "entity.re8joymod.sniperammo": "狙击枪子弹",
    
    • 1
    • 2
    • 3

    8.保存项目,运行游戏测试:

    主手时狙击枪形态:

    mainhand.png

    按’F’键切换至副手时狙击枪形态

    kaijing.png

    Pong! Pong!

  • 相关阅读:
    批量归一化(部分理解)
    【设计模式】单例模式
    Go语言中的面向对象编程(OOP)
    多个Map进行内容合并
    嵌入式分享合集51
    9.20金融科技(比特币)
    Win10只读文件夹怎么删除
    LeetCode //C - 67. Add Binary
    1110 区块反转 分数 25
    【代码随想录】算法训练营 第十三天 第五章 栈与队列 Part 3
  • 原文地址:https://blog.csdn.net/Jay_fearless/article/details/125629976