Jump to content

[1.20.1] How to add your own texture for arrow


Recommended Posts

Posted

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?

Posted

I made some experiments and I saw that only spectral arrow spawns with id "minecraft:spectral_arrow". Every other arrow, including my, spawns with id "minecraft:arrow". Is it possible to fix it someway?

Posted (edited)

Maybe I should extend AbstractArrow class instead of Arrow class like the SpectralArrow class does?

Edited by btuh

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.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I need to know what mod is doing this crash, i mean the mod xenon is doing the crash but i want to know who mod is incompatible with xenon, but please i need to know a solution if i need to replace xenon, i cant use optifine anymore and all the other mods i tried(sodium, lithium, vulkan, etc) doesn't work, it crash the game.
    • I have been trying to solve a consistent crashing issue on my brother's computer where it will crash during the "Scanning Mod Candidates" phase of the loading process that starts when you click the play button on the Minecraft launcher. The issue seems to stem from a missing library that it mentions in the log file I provide below. I might I'm missing the bigger issue here for a smaller one but hopefully someone can find what I'm missing. Here's all of the stuff that I've been able to figure out so far: 1. It has nothing to do with mods, the crash happened with a real modpack, and even when I made a custom modpack and launched it without putting ANY mods into it (That is where the log file comes from by the way). 2. I have tried to find this class like a file in the Minecraft folders, but I've had no luck finding it (I don't think it works like that, but since I really don't understand how it works, I just figured I'd try). 3. I haven't seen anyone else have this issue before. 4. I know that my modpack (with mods) does work since I've run it on my computer, and it works fantastic. For some reason my brother's computer can't seem to run anything through curseforge. 5. This is for Minecraft version 1.20.1, Minecraft launcher version 3.4.50-2.1.3, forge 47.3.0, and curseforge app version 1.256.0.21056 6. My brother is using a Dell laptop from 6 years ago running Windows 10 (If you think more info on this would help, please ask as I do have it. I'm just choosing not to put it here for now). 7. I have reinstalled the curseforge app and installed Minecraft version 1.20.1. I have not reinstalled Minecraft or forge 47.3.0 but I didn't know if that would help. 8. I had an error code of 1 Please let me know if there is anything else that I am missing that you would like me to add to this post/add in a comment! Lastly, many thanks in advance to whoever can help! ------------- LOG FILE (latest.log) ------------- (from /Users/<NAME OF USER>/cursforge/minecraft/Instances/<THE NAME OF MY EMPTY MODPACK>/logs/latest.log) (This was made after running an empty modpack with same versions for all apps) ("[REDACTED]" is not the actual text from the log, it is me replacing text I figured wouldn't be necessary for fixing and would hurt my privacy) https://pastebin.com/hxXvGGEK ------------- DEBUG.LOG (I realized that I should have put this here first after I had done all of the work on putting latest.log in) -------------------- (again, "[REDACTED]" is not the actual text from the log, it is me replacing text I figured wouldn't be necessary for fixing and would hurt my privacy) https://pastebin.com/Fmh8GHYs
    • Pastebin... https://pastebin.com/Y3iZ85L5   Brand new profile, does not point to a mod as far as I can tell, my fatal message just has something about mixins. Don't know much about reading logs like this, but am genuinely stuck, please help. Java updated, pc restarted.
    • I was playing minecraft, forge 47.3.0 and 1.20.1, but when i tried to play minecraft now only crashes, i need help please. here is the crash report: https://securelogger.net/files/e6640a4f-9ed0-4acc-8d06-2e500c77aaaf.txt
  • Topics

  • Who's Online (See full list)

×
×
  • Create New...

Important Information

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