Jump to content

[1.20.1] How to add your own texture for arrow


btuh

Recommended Posts

I'm creating an arrow which, for some reason, uses vanilla texture, not the one that I want it to use.

Arrow code

import net.minecraft.core.Direction;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.nbt.*;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.TraceableEntity;
import net.minecraft.world.entity.projectile.Arrow;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;

public class TntArrow extends Arrow implements TraceableEntity {

    private static final EntityDataAccessor<Integer> DATA_FUSE_ID
            = SynchedEntityData.defineId(TntArrow.class, EntityDataSerializers.INT);

    public TntArrow(EntityType<? extends TntArrow> entityType, Level level) {
        super(entityType, level);
    }



    public int getFuse() {
        return entityData.get(DATA_FUSE_ID);
    }

    public void setFuse(int fuse) {
        this.entityData.set(DATA_FUSE_ID, fuse);
    }


    public TntArrow(Level p_36866_, LivingEntity p_36867_) {
        super(p_36866_, p_36867_);
    }

    @Override
    protected void onHitEntity(@NotNull EntityHitResult result) {
        super.onHitEntity(result);
        var tnt = Objects.requireNonNull(EntityType.TNT.create(result.getEntity().level()));
        tnt.setPos(result.getLocation().get(Direction.Axis.X),
                result.getLocation().get(Direction.Axis.Y),
                result.getLocation().get(Direction.Axis.Z));
        tnt.setFuse(0);
        tnt.tick();
    }

    @Override
    public CompoundTag serializeNBT() {
        CompoundTag tag = super.serializeNBT();
        tag.putInt("Fuse", getFuse());
        return tag;
    }

    @Override
    public void deserializeNBT(CompoundTag tag) {
        super.deserializeNBT(tag);
        setFuse(tag.getInt("Fuse"));
    }

    @Override
    public void defineSynchedData() {
        super.defineSynchedData();
        entityData.define(DATA_FUSE_ID, 80);
    }

    @Override
    protected void onHitBlock(@NotNull BlockHitResult result) {
        super.onHitBlock(result);
        var tnt = Objects.requireNonNull(EntityType.TNT.create(level()));
        tnt.setPos(result.getLocation().with(Direction.Axis.Y, result.getLocation().y + 1));
        tnt.setFuse(0);
        tnt.tick();
        discard();
    }

    @Override
    public void tick() {
        super.tick();
        int fuse = getFuse();
        setFuse(--fuse);
        if (fuse <= 0) {
            discard();
            if(!level().isClientSide) {
                var tnt = Objects.requireNonNull(EntityType.TNT.create(level()));
                tnt.setPos(getX(), getY(), getZ());
                tnt.setFuse(0);
                tnt.tick();
            }
        } else {
            updateInWaterStateAndDoFluidPushing();
            if (level().isClientSide) {
                level().addParticle(ParticleTypes.SMOKE,
                        this.getX(), this.getY() + 0.5D,
                        this.getZ(), 0.0D, 0.0D, 0.0D);
            }
        }
    }


}

Arrow item code

import com.mojang.logging.LogUtils;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.AbstractArrow;
import net.minecraft.world.item.ArrowItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;

import static net.minecraft.world.item.enchantment.Enchantments.INFINITY_ARROWS;


public class TntArrowItem extends ArrowItem {
    private static final Logger LOGGER = LogUtils.getLogger();
    public TntArrowItem(Properties properties) {
        super(properties);
    }

    @Override
    @NotNull
    public AbstractArrow createArrow(@NotNull Level level,
                                     @NotNull ItemStack stack,
                                     @NotNull LivingEntity livingEntity) {
        LOGGER.info("TntArrow creation");
        TntArrow arrow = new TntArrow(level, livingEntity);
        arrow.setEffectsFromItem(stack);
        return arrow;
    }

    public boolean isInfinite(@NotNull ItemStack stack,
                              @NotNull ItemStack bow,
                              @NotNull Player player) {
        int enchant = EnchantmentHelper.getTagEnchantmentLevel(INFINITY_ARROWS, bow);
        return enchant > 0 && this.getClass() == TntArrowItem.class;
    }
}

Arrow renderer code

import net.minecraft.client.renderer.entity.ArrowRenderer;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class TntArrowRenderer extends ArrowRenderer<TntArrow> {

    @NotNull
    private static final ResourceLocation TEXTURE
            = new ResourceLocation(Main.MOD_ID, "textures/entity/projectiles/tnt_arrow.png");

    public TntArrowRenderer(@NotNull EntityRendererProvider.Context ctx) {
        super(ctx);
    }

    @Override
    @NotNull
    public ResourceLocation getTextureLocation(@Nullable TntArrow arrow) {
        return TEXTURE;
    }
}

Arrow model code

// Made with Blockbench 4.8.3
// Exported for Minecraft version 1.17 or later with Mojang mappings
// Paste this class into your mod and generate all required imports
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.model.EntityModel;
import net.minecraft.client.model.geom.ModelLayerLocation;
import net.minecraft.client.model.geom.ModelPart;
import net.minecraft.client.model.geom.PartPose;
import net.minecraft.client.model.geom.builders.*;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import ru.fokinatorr.moarrows.Main;
import ru.fokinatorr.moarrows.tnt_arrow.TntArrow;

public class TntArrowModel extends EntityModel<TntArrow> {
	// This layer location should be baked with EntityRendererProvider.Context in the entity renderer and passed into this model's constructor
	public static final ModelLayerLocation LAYER_LOCATION = new ModelLayerLocation(new ResourceLocation(Main.MOD_ID, "tnt_arrow"), "main");
	private final ModelPart arrow;
	private final ModelPart tnt;

	public TntArrowModel(ModelPart root) {
		this.arrow = root.getChild("arrow");
		this.tnt = root.getChild("tnt");
	}

	public static LayerDefinition createBodyLayer() {
		MeshDefinition meshDefinition = new MeshDefinition();
		PartDefinition partDefinition = meshDefinition.getRoot();

		PartDefinition arrow = partDefinition.addOrReplaceChild("arrow",
				CubeListBuilder.create()
						.texOffs(-5, 0)
						.addBox(-9.5F, -2.75F, -1.13F,
								19.5F, 0.0F, 5.0F,
								new CubeDeformation(0.0F))
						.texOffs(4, 6)
						.addBox(-9.0F, -5.2F,
								-1.0F, 0.0F, 5.0F, 5.0F,
								new CubeDeformation(0.0F)),
				PartPose.offset(0.0F, 24.0F, 0.0F));

		arrow.addOrReplaceChild("arrow_2_r1",
				CubeListBuilder.create().
						texOffs(-5, 0)
						.addBox(-15.6F, -1.5F, -0.75F,
								19.5F, 0.0F, 5.0F,
								new CubeDeformation(0.0F)),
				PartPose.offsetAndRotation(6.1F, -4.25F, 0.0F,
						-1.5708F, 0.0F, 0.0F));

		partDefinition.addOrReplaceChild("tnt",
				CubeListBuilder.create()
						.texOffs(0, 18)
						.addBox(-6.75F, -7.0F, -6.5F,
								16.0F, 16.0F, 16.0F,
								new CubeDeformation(-5.75F)),
				PartPose.offset(-1.0F, 20.75F, 0.0F));

		return LayerDefinition.create(meshDefinition, 64, 64);
	}

	@Override
	public void setupAnim(@NotNull TntArrow arrow,
						  float limbSwing,
						  float limbSwingAmount,
						  float ageInTicks, float netHeadYaw, float headPitch) {

	}

	@Override
	public void renderToBuffer(@NotNull PoseStack poseStack,
							   @NotNull VertexConsumer vertexConsumer,
							   int packedLight,
							   int packedOverlay,
							   float red,
							   float green,
							   float blue,
							   float alpha) {
		arrow.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha);
		tnt.render(poseStack, vertexConsumer, packedLight, packedOverlay, red, green, blue, alpha);
	}
}

ClientModEvents

import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.EntityRenderersEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

@Mod.EventBusSubscriber(modid = Main.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
public final class ClientModEvents {
    @SubscribeEvent
    public static void registerRenderers(EntityRenderersEvent.RegisterRenderers event) {
        event.registerEntityRenderer(_Entities.TNT_ARROW.get(), TntArrowRenderer::new);
    }

    @SubscribeEvent
    public static void registerLayerDefinitions(EntityRenderersEvent.RegisterLayerDefinitions event) {
        event.registerLayerDefinition(TntArrowModel.LAYER_LOCATION, TntArrowModel::createBodyLayer);
    }
}

_Entities

import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobCategory;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;

public class _Entities {

    public static final DeferredRegister<EntityType<?>> ENTITIES =
            DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, Main.MOD_ID);

    public static final RegistryObject<EntityType<TntArrow>> TNT_ARROW = ENTITIES.register("tnt_arrow",
            () -> EntityType.Builder.<TntArrow>of(TntArrow::new, MobCategory.MISC)
                    .sized(.5f, .5f)
                    .clientTrackingRange(4)
                    .updateInterval(20)
                    .build(new ResourceLocation(Main.MOD_ID, "tnt_arrow").toString()));

    private _Entities() {}
}

Any ideas?

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.



×
×
  • Create New...

Important Information

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