Jump to content

Shootable entity stops rendering upon contact with player's face


humanoidbob99

Recommended Posts

Hi! I have created an entity that can be shot from a laser gun. However, when the laser hits the player, it stops rendering. It still hits the ground, though. If I move backwards really fast, it spawns in front of my face instead of inside, and renders until it hits an entity or block.

Here are all the relevant classes:

EntityLaser:

package humanoidbob99.SciFiMod;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.List;

import net.minecraft.enchantment.EnchantmentThorns;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.IProjectile;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.projectile.EntityFireball;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagDouble;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.packet.Packet70GameEvent;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumMovingObjectType;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;

public class EntityLaser extends Entity
{
private int xTile = -1;
private int yTile = -1;
private int zTile = -1;
private int inTile = 0;
private boolean inGround = false;
public EntityLiving shootingEntity;
private int ticksAlive = 0;
private int ticksInAir = 0;
public double accelerationX;
public double accelerationY;
public double accelerationZ;
private double damage;
private int fire = 0;
public float yOffset;
private boolean firstUpdate;

public double getDamage(){
	return this.damage;
}

public EntityLaser setDamage(double newDamage){
	this.damage = newDamage;
	return this;
}

protected void entityInit() {}

@SideOnly(Side.CLIENT)

/**
 * Checks if the entity is in range to render by using the past in distance and comparing it to its average edge
 * length * 64 * renderDistanceWeight Args: distance
 */
public boolean isInRangeToRenderDist(double par1)
{
	double d1 = this.boundingBox.getAverageEdgeLength() * 4.0D;
	d1 *= 64.0D;
	return par1 < d1 * d1;
}

public EntityLaser(World par1World)
{
	super(par1World);
	this.setSize(0.5F, 0.5F);
}

public EntityLaser(World par1World, double par2, double par4, double par6, double par8, double par10, double par12)
{
	super(par1World);
	this.setSize(0.5F, 0.5F);
	this.setLocationAndAngles(par2, par4, par6, this.rotationYaw, this.rotationPitch);
	this.setPosition(par2, par4, par6);
	this.accelerationX = 0;
	this.accelerationY = 0;
	this.accelerationZ = 0;
}

public EntityLaser(World par1World, EntityLiving par2EntityLiving, double par3, double par5, double par7)
{
	super(par1World);
	this.setFire(0);
	this.shootingEntity = par2EntityLiving;
	this.setSize(0.5F, 0.5F);
	this.setLocationAndAngles(par2EntityLiving.posX, par2EntityLiving.posY + par2EntityLiving.getEyeHeight() - 0.2, par2EntityLiving.posZ, par2EntityLiving.rotationYaw, par2EntityLiving.rotationPitch);
	this.setPosition(this.posX, this.posY, this.posZ);
	par1World.playSoundAtEntity(this, "fire.fire", 1.0F, 1.0F);
	this.yOffset = 0F;
	this.motionX = (double)(-MathHelper.sin(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI));
	this.motionZ = (double)(MathHelper.cos(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI));
	this.motionY = (double)(-MathHelper.sin(this.rotationPitch / 180.0F * (float)Math.PI));
	//this.posX += 1.5 * this.motionX;
	//this.posZ += 1.5 * this.motionZ;
	//this.posY += 1.5 * this.motionY;
	this.accelerationX = 0;
	this.accelerationY = 0;
	this.accelerationZ = 0;
}

/**
 * Called to update the entity's position/logic.
 */
public void onUpdate()
{
	if (this.ticksAlive >= 40 || (!this.worldObj.isRemote && (this.shootingEntity != null && this.shootingEntity.isDead || !this.worldObj.blockExists((int)this.posX, (int)this.posY, (int)this.posZ))))
	{
		this.setDead();
		this.worldObj.playSoundAtEntity(this, "fire.ignite", 1.0F, 1.0F);
	}
	else
	{
		this.onEntityUpdate();

		++this.ticksAlive;

		//this.worldObj.spawnParticle("crit", this.posX, this.posY, this.posZ, 0, 0, 0);

		//if(this.firstUpdate){
		//	this.worldObj.playSoundAtEntity(this, "fire.ignite", 1.0F, 1.0F);
		//	System.out.println("Spawned laser at (" + Double.toString(posX) + ", "+ Double.toString(posY) + ", "+ Double.toString(posZ) + ").");
		//}

		Vec3 vec3 = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX, this.posY, this.posZ);
		Vec3 vec31 = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
		MovingObjectPosition movingobjectposition = this.worldObj.rayTraceBlocks(vec3, vec31);
		vec3 = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX, this.posY, this.posZ);
		vec31 = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);

            if (movingobjectposition != null)
            {
                vec31 = this.worldObj.getWorldVec3Pool().getVecFromPool(movingobjectposition.hitVec.xCoord, movingobjectposition.hitVec.yCoord, movingobjectposition.hitVec.zCoord);
            }
            
		Entity entity = null;
		List list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox.addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D));
		double d0 = 0.0D;

		for (int j = 0; j < list.size(); ++j)
		{
			Entity entity1 = (Entity)list.get(j);

			if (entity1.canBeCollidedWith() && !entity1.isEntityEqual(this.shootingEntity))
			{
				float f = 0.3F;
				AxisAlignedBB axisalignedbb = entity1.boundingBox.expand((double)f, (double)f, (double)f);
				MovingObjectPosition movingobjectposition1 = axisalignedbb.calculateIntercept(vec3, vec31);

				if (movingobjectposition1 != null)
				{
					double d1 = vec3.distanceTo(movingobjectposition1.hitVec);

					if (d1 < d0 || d0 == 0.0D)
					{
						entity = entity1;
						d0 = d1;
					}
				}
			}
		}

		if (entity != null)
		{
			movingobjectposition = new MovingObjectPosition(entity);
		}

		if (movingobjectposition != null)
		{
			this.onImpact(movingobjectposition);
			this.worldObj.playSoundAtEntity(this.shootingEntity, "fire.ignite", 1.0F, 1.0F);
		}

		this.posX += this.motionX;
		this.posY += this.motionY;
		this.posZ += this.motionZ;
		float f1 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
		this.rotationYaw = (float)(Math.atan2(this.motionZ, this.motionX) * 180.0D / Math.PI) + 90.0F;

		for (this.rotationPitch = (float)(Math.atan2((double)f1, this.motionY) * 180.0D / Math.PI) - 90.0F; this.rotationPitch - this.prevRotationPitch < -180.0F; this.prevRotationPitch -= 360.0F)
		{
			;
		}

		while (this.rotationPitch - this.prevRotationPitch >= 180.0F)
		{
			this.prevRotationPitch += 360.0F;
		}

		while (this.rotationYaw - this.prevRotationYaw < -180.0F)
		{
			this.prevRotationYaw -= 360.0F;
		}

		while (this.rotationYaw - this.prevRotationYaw >= 180.0F)
		{
			this.prevRotationYaw += 360.0F;
		}

		this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F;
		this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F;
		float f2 = this.getMotionFactor();

		this.motionX += this.accelerationX;
		this.motionY += this.accelerationY;
		this.motionZ += this.accelerationZ;
		this.motionX *= (double)f2;
		this.motionY *= (double)f2;
		this.motionZ *= (double)f2;
		this.setPosition(this.posX, this.posY, this.posZ);
	}
}

    public void onEntityUpdate()
    {
        this.worldObj.theProfiler.startSection("entityBaseTick");

        if (this.ridingEntity != null && this.ridingEntity.isDead)
        {
            this.ridingEntity = null;
        }

        this.prevDistanceWalkedModified = this.distanceWalkedModified;
        this.prevPosX = this.posX;
        this.prevPosY = this.posY;
        this.prevPosZ = this.posZ;
        this.prevRotationPitch = this.rotationPitch;
        this.prevRotationYaw = this.rotationYaw;
        int i;

        if (!this.worldObj.isRemote && this.worldObj instanceof WorldServer)
        {
            this.worldObj.theProfiler.startSection("portal");
            MinecraftServer minecraftserver = ((WorldServer)this.worldObj).getMinecraftServer();
            i = this.getMaxInPortalTime();

            if (this.inPortal)
            {
                if (minecraftserver.getAllowNether())
                {
                    if (this.ridingEntity == null && this.timeInPortal++ >= i)
                    {
                        this.timeInPortal = i;
                        this.timeUntilPortal = this.getPortalCooldown();
                        byte b0;

                        if (this.worldObj.provider.dimensionId == -1)
                        {
                            b0 = 0;
                        }
                        else
                        {
                            b0 = -1;
                        }

                        this.travelToDimension(b0);
                    }

                    this.inPortal = false;
                }
            }
            else
            {
                if (this.timeInPortal > 0)
                {
                    this.timeInPortal -= 4;
                }

                if (this.timeInPortal < 0)
                {
                    this.timeInPortal = 0;
                }
            }

            if (this.timeUntilPortal > 0)
            {
                --this.timeUntilPortal;
            }

            this.worldObj.theProfiler.endSection();
        }

        if (this.isSprinting() && !this.isInWater())
        {
            int j = MathHelper.floor_double(this.posX);
            i = MathHelper.floor_double(this.posY - 0.20000000298023224D - (double)this.yOffset);
            int k = MathHelper.floor_double(this.posZ);
            int l = this.worldObj.getBlockId(j, i, k);

            if (l > 0)
            {
                this.worldObj.spawnParticle("tilecrack_" + l + "_" + this.worldObj.getBlockMetadata(j, i, k), this.posX + ((double)this.rand.nextFloat() - 0.5D) * (double)this.width, this.boundingBox.minY + 0.1D, this.posZ + ((double)this.rand.nextFloat() - 0.5D) * (double)this.width, -this.motionX * 4.0D, 1.5D, -this.motionZ * 4.0D);
            }
        }

        this.handleWaterMovement();

        if (this.worldObj.isRemote)
        {
            this.fire = 0;
        }
        else if (this.fire > 0)
        {
            if (this.isImmuneToFire)
            {
                this.fire -= 4;

                if (this.fire < 0)
                {
                    this.fire = 0;
                }
            }
            else
            {
                if (this.fire % 20 == 0)
                {
                    this.attackEntityFrom(DamageSource.onFire, 1);
                }

                --this.fire;
            }
        }

        if (this.handleLavaMovement())
        {
            this.setOnFireFromLava();
            this.fallDistance *= 0.5F;
        }

        if (this.posY < -64.0D)
        {
            this.kill();
        }

        if (!this.worldObj.isRemote)
        {
            this.setFlag(0, this.fire > 0);
            this.setFlag(2, this.ridingEntity != null && ridingEntity.shouldRiderSit());
        }

        this.firstUpdate = false;
        this.worldObj.theProfiler.endSection();
    }
    
/**
 * Return the motion factor for this projectile. The factor is multiplied by the original motion.
 */
protected float getMotionFactor()
{
	return 1F;
}

/**
 * Called when this EntityLaser hits a block or entity.
 */
protected void onImpact(MovingObjectPosition movingobjectposition) {
	boolean kill = true;
	if (movingobjectposition != null)
	{
		if(movingobjectposition.typeOfHit == EnumMovingObjectType.ENTITY){
			if(!movingobjectposition.entityHit.isEntityEqual(this.shootingEntity))
			{

				int i1 = MathHelper.ceiling_double_int(this.getDamage());
				DamageSource damagesource = null;

				if (this.shootingEntity == null)
				{
					damagesource = SciFiMod.causeLaserDamage(this, this);
				}
				else
				{
					damagesource = SciFiMod.causeLaserDamage(this, this.shootingEntity);
				}

				if (movingobjectposition.entityHit.attackEntityFrom(damagesource, i1)){
					if (movingobjectposition.entityHit instanceof EntityLiving)
					{
						EntityLiving entityliving = (EntityLiving)movingobjectposition.entityHit;

						if (this.shootingEntity != null)
						{
							EnchantmentThorns.func_92096_a(this.shootingEntity, entityliving, this.rand);
						}

						if (this.shootingEntity != null && movingobjectposition.entityHit != this.shootingEntity && movingobjectposition.entityHit instanceof EntityPlayer && this.shootingEntity instanceof EntityPlayerMP)
						{
							((EntityPlayerMP)this.shootingEntity).playerNetServerHandler.sendPacketToPlayer(new Packet70GameEvent(6, 0));
						}
					}
					else{
						kill = false;
					}
				}
			}
			else{
				kill = false;
			}
		}
		//else if(movingobjectposition.typeOfHit == EnumMovingObjectType.TILE){
		//	if(this.worldObj.isAirBlock(movingobjectposition.blockX, movingobjectposition.blockY, movingobjectposition.blockZ)){
		//		kill = false;
		//		//System.out.println("set kill to false");
		//	}
		//	else{
		//		//System.out.println("asdf");
		//	}
		//}
		if(kill){
			this.setDead();
		}
	}
}

/**
 * (abstract) Protected helper method to write subclass entity data to NBT.
 */
public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound)
{
	par1NBTTagCompound.setShort("xTile", (short)this.xTile);
	par1NBTTagCompound.setShort("yTile", (short)this.yTile);
	par1NBTTagCompound.setShort("zTile", (short)this.zTile);
	par1NBTTagCompound.setByte("inTile", (byte)this.inTile);
	par1NBTTagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0));
	par1NBTTagCompound.setTag("direction", this.newDoubleNBTList(new double[] {this.motionX, this.motionY, this.motionZ}));
}

/**
 * (abstract) Protected helper method to read subclass entity data from NBT.
 */
public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound)
{
	this.xTile = par1NBTTagCompound.getShort("xTile");
	this.yTile = par1NBTTagCompound.getShort("yTile");
	this.zTile = par1NBTTagCompound.getShort("zTile");
	this.inTile = par1NBTTagCompound.getByte("inTile") & 255;
	this.inGround = par1NBTTagCompound.getByte("inGround") == 1;

	if (par1NBTTagCompound.hasKey("direction"))
	{
		NBTTagList nbttaglist = par1NBTTagCompound.getTagList("direction");
		this.motionX = ((NBTTagDouble)nbttaglist.tagAt(0)).data;
		this.motionY = ((NBTTagDouble)nbttaglist.tagAt(1)).data;
		this.motionZ = ((NBTTagDouble)nbttaglist.tagAt(2)).data;
	}
	else
	{
		this.setDead();
	}
}

/**
 * Returns true if other Entities should be prevented from moving through this Entity.
 */
public boolean canBeCollidedWith()
{
	return false;
}

public float getCollisionBorderSize()
{
	return 1.0F;
}

/**
 * Called when the entity is attacked.
 */
public boolean attackEntityFrom(DamageSource par1DamageSource, int par2)
{
	return false;
}

@SideOnly(Side.CLIENT)
public float getShadowSize()
{
	return 0.0F;
}

/**
 * Gets how bright this entity is.
 */
public float getBrightness(float par1)
{
	return 1.0F;
}

@SideOnly(Side.CLIENT)
public int getBrightnessForRender(float par1)
{
	return 15728880;
}

}

SciFiMod:

package humanoidbob99.SciFiMod;

import humanoidbob99.SciFiMod.client.ClientProxy;
import humanoidbob99.SciFiMod.common.core.handlers.CraftingHandler;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBow;
import net.minecraft.item.ItemStack;
import net.minecraft.src.ModLoader;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSourceIndirect;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PostInit;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;

@Mod(modid="SciFiMod", name="SciFiMod", version="0.0.0")
@NetworkMod(clientSideRequired=true, serverSideRequired=false)
public class SciFiMod {

// The instance of your mod that Forge uses.
@Instance("SciFiMod")
public static SciFiMod instance;

public static final Block blockScrith = new BlockScrith(1499).setHardness(50.0F).setResistance(2000.0F).setStepSound(Block.soundMetalFootstep).setCreativeTab(CreativeTabs.tabBlock).setUnlocalizedName("blockScrith");

public static final SciFiModItem scrithDust = (SciFiModItem) new SciFiModItem(21499).setTextureFile(CommonProxy.SCRITHDUST_PNG).setUnlocalizedName("scrithDust").setCreativeTab(CreativeTabs.tabMaterials);
public static final Item bowScrith = new BowScrith(21500).setUnlocalizedName("bowScrith");
public static final SciFiModItem scrithWire = (SciFiModItem) new SciFiModItem(21501).setTextureFile(CommonProxy.SCRITHWIRE_PNG).setUnlocalizedName("scrithWire").setCreativeTab(CreativeTabs.tabMaterials);
public static final SciFiModItem ingotScrith = (SciFiModItem) new SciFiModItem(21502).setTextureFile(CommonProxy.INGOTSCRITH_PNG).setUnlocalizedName("ingotScrith").setCreativeTab(CreativeTabs.tabMaterials);
public static final SciFiModItem arrowScrith = (SciFiModItem) new SciFiModItem(21503).setTextureFile(CommonProxy.ARROWSCRITH_PNG).setUnlocalizedName("arrowScrith").setCreativeTab(CreativeTabs.tabCombat);
public static final SciFiModItem redstonePutty = (SciFiModItem) new SciFiModItem(21504).setTextureFile(CommonProxy.REDSTONEPUTTY_PNG).setUnlocalizedName("redstonePutty").setCreativeTab(CreativeTabs.tabMaterials);
public static final SciFiModItem redstoneShard = (SciFiModItem) new SciFiModItem(21505).setTextureFile(CommonProxy.REDSTONESHARD_PNG).setUnlocalizedName("redstoneShard").setCreativeTab(CreativeTabs.tabCombat);
public static final SciFiModItem ironFletching = (SciFiModItem) new SciFiModItem(21506).setTextureFile(CommonProxy.IRONFLETCHING_PNG).setUnlocalizedName("ironFletching").setCreativeTab(CreativeTabs.tabCombat);
public static final SciFiModIconItem iconItem = (SciFiModIconItem) new SciFiModIconItem(21507);
public static final LaserGun laserGun = (LaserGun) new LaserGun(21508).setUnlocalizedName("laserGun");
public static final SciFiModItem depletedRedstonePutty = (SciFiModItem) new SciFiModItem(21509).setTextureFile(CommonProxy.REDSTONEPUTTY_PNG).setUnlocalizedName("depletedRedstonePutty").setCreativeTab(CreativeTabs.tabMaterials);

public static DamageSource causeArrowScrithDamage(EntityArrowScrith par0EntityArrowScrith, Entity par1Entity)
{
	return (new EntityDamageSourceIndirect("arrowScrith", par0EntityArrowScrith, par1Entity)).setProjectile();
}
public static DamageSource causeLaserDamage(EntityLaser par0EntityLaser, Entity par1Entity)
{
	return (new EntityDamageSourceIndirect("laser", par0EntityLaser, par1Entity).setExplosion());
}

// Says where the client and server 'proxy' code is loaded.
@SidedProxy(clientSide="humanoidbob99.SciFiMod.client.ClientProxy", serverSide="humanoidbob99.SciFiMod.CommonProxy")
public static ClientProxy proxy;

@PreInit
public void preInit(FMLPreInitializationEvent event) {
	// Stub Method
}

@Init
public void load(FMLInitializationEvent event) {
	LanguageRegistry.addName(blockScrith, "Scrith Block");
	LanguageRegistry.addName(scrithDust, "Scrith Dust");
	LanguageRegistry.addName(bowScrith, "Scrith Bow");
	LanguageRegistry.addName(scrithWire, "Scrith Cord");
	LanguageRegistry.addName(ingotScrith, "Scrith Ingot");
	LanguageRegistry.addName(arrowScrith, "Scrith Arrow");
	LanguageRegistry.addName(redstonePutty, "Redstone Putty");
	LanguageRegistry.addName(redstoneShard, "Redstone Shard");
	LanguageRegistry.addName(ironFletching, "Iron Fletching");
	LanguageRegistry.addName(laserGun, "Laser Gun");
	LanguageRegistry.addName(depletedRedstonePutty, "Depleted Redstone Putty");

	int arrowScrithEntityID = EntityRegistry.findGlobalUniqueEntityId();
	EntityRegistry.registerGlobalEntityID(EntityArrowScrith.class, "arrowScrith", arrowScrithEntityID);
	EntityRegistry.registerModEntity(EntityArrowScrith.class, "arrowScrith", arrowScrithEntityID, this, 64, 1, true);
	int laserEntityID = EntityRegistry.findGlobalUniqueEntityId();
	EntityRegistry.registerGlobalEntityID(EntityLaser.class, "laser", laserEntityID);
	EntityRegistry.registerModEntity(EntityLaser.class, "laser", laserEntityID, this, 64, 1, true);

	RenderingRegistry.registerEntityRenderingHandler(EntityArrowScrith.class, new RenderArrowScrith());
	RenderingRegistry.registerEntityRenderingHandler(EntityLaser.class, new RenderLaser(1.0F));

	System.out.println("Scrith Arrow Entity ID is " + Integer.toString(arrowScrithEntityID));
	System.out.println("Laser Entity ID is " + Integer.toString(laserEntityID));

	proxy.registerRenderers();

	GameRegistry.registerCraftingHandler(new CraftingHandler());

	GameRegistry.addRecipe(new ItemStack(arrowScrith,9), new Object[]{"s","b","f",'s',this.redstoneShard,'b',Item.blazeRod,'f',this.ironFletching});
	GameRegistry.addRecipe(new ItemStack(bowScrith), new Object[]{" bw", "b w", " bw",'b',Item.blazeRod,'w',this.ironFletching});
	GameRegistry.addRecipe(new ItemStack(scrithWire,9), new Object[]{"i","i","i",'i',this.ingotScrith});
	GameRegistry.addRecipe(new ItemStack(blockScrith,1), new Object[]{"iii","iii","iii",'i',this.ingotScrith});
	GameRegistry.addRecipe(new ItemStack(ingotScrith,9), new Object[]{"b",'b',this.blockScrith});
	GameRegistry.addRecipe(new ItemStack(redstonePutty, , new Object[]{"rrr", "rbr", "rrr", 'b', Item.bucketWater, 'r', Item.redstone});
	GameRegistry.addRecipe(new ItemStack(laserGun, 1), new Object[]{"ssd", "sgq", 's', this.ingotScrith, 'd', Item.diamond, 'g', Item.lightStoneDust, 'q', Item.netherQuartz});

	GameRegistry.addShapelessRecipe(new ItemStack(scrithDust,4), new Object[]{Block.obsidian,Block.obsidian,Item.diamond,Item.ingotGold,Item.ingotGold,Item.ingotGold,Item.ingotIron,Item.ingotIron,Item.ingotIron});
	GameRegistry.addShapelessRecipe(new ItemStack(ironFletching, 3), new Object[]{Item.ingotIron});

	for(int iterator = 1; iterator <= 31; iterator++){
		GameRegistry.addShapelessRecipe(new ItemStack(depletedRedstonePutty, 1), new Object[]{this.redstonePutty, new ItemStack(laserGun, 1, iterator)});
	}

	GameRegistry.addSmelting(redstonePutty.itemID, new ItemStack(redstoneShard), 0.0F);

	GameRegistry.registerBlock(blockScrith, "blockScrith");
	MinecraftForge.setBlockHarvestLevel(blockScrith, "pickaxe", 4);
}

@PostInit
public void postInit(FMLPostInitializationEvent event) {
	// Stub Method
}
}

RenderLaser:

package humanoidbob99.SciFiMod;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;

import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.entity.Entity;
import humanoidbob99.SciFiMod.EntityLaser;
import net.minecraft.item.Item;
import net.minecraft.util.Icon;

public class RenderLaser extends Render {
    private float field_77002_a;

    public RenderLaser(float par1)
    {
        this.field_77002_a = par1;
    }

    public void doRenderLaser(EntityLaser par1EntityLaser, double par2, double par4, double par6, float par8, float par9)
    {
        GL11.glPushMatrix();
        GL11.glTranslatef((float)par2, (float)par4, (float)par6);
        GL11.glEnable(GL12.GL_RESCALE_NORMAL);
        float f2 = this.field_77002_a;
        GL11.glScalef(f2 / 1.0F, f2 / 1.0F, f2 / 1.0F);
        Icon icon = SciFiMod.iconItem.getIconFromDamage(0);
        this.loadTexture("/gui/items.png");
        Tessellator tessellator = Tessellator.instance;
        float f3 = icon.getMinU();
        float f4 = icon.getMaxU();
        float f5 = icon.getMinV();
        float f6 = icon.getMaxV();
        float f7 = 1.0F;
        float f8 = 0.5F;
        float f9 = 0.25F;
        GL11.glRotatef(180.0F - this.renderManager.playerViewY, 0.0F, 1.0F, 0.0F);
        GL11.glRotatef(-this.renderManager.playerViewX, 1.0F, 0.0F, 0.0F);
        tessellator.startDrawingQuads();
        tessellator.setNormal(0.0F, 1.0F, 0.0F);
        tessellator.addVertexWithUV((double)(0.0F - f8), (double)(0.0F - f9), 0.0D, (double)f3, (double)f6);
        tessellator.addVertexWithUV((double)(f7 - f8), (double)(0.0F - f9), 0.0D, (double)f4, (double)f6);
        tessellator.addVertexWithUV((double)(f7 - f8), (double)(1.0F - f9), 0.0D, (double)f4, (double)f5);
        tessellator.addVertexWithUV((double)(0.0F - f8), (double)(1.0F - f9), 0.0D, (double)f3, (double)f5);
        tessellator.draw();
        GL11.glDisable(GL12.GL_RESCALE_NORMAL);
        GL11.glPopMatrix();
    }

    /**
     * Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then
     * handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic
     * (Render<T extends Entity) and this method has signature public void doRender(T entity, double d, double d1,
     * double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that.
     */
    @Override
    public void doRender(Entity par1Entity, double par2, double par4, double par6, float par8, float par9)
    {
        this.doRenderLaser((EntityLaser)par1Entity, par2, par4, par6, par8, par9);
    }
}

LaserGun:

package humanoidbob99.SciFiMod;

import java.util.List;

import humanoidbob99.SciFiMod.client.ClientProxy;
import humanoidbob99.SciFiMod.EntityLaser;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.entity.projectile.EntityLargeFireball;
import net.minecraft.item.EnumAction;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBow;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.Icon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;

import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.ArrowLooseEvent;
import net.minecraftforge.event.entity.player.ArrowNockEvent;

public class LaserGun extends Item
{
public static final String[] laserIconNameArray = new String[] {ClientProxy.LASERGUN0_PNG, ClientProxy.LASERGUN1_PNG};
@SideOnly(Side.CLIENT)
private Icon[] iconArray;
private int iconId = 0;

public LaserGun(int par1)
{
	super(par1);
	this.maxStackSize = 1;
	this.setNoRepair();
	this.setCreativeTab(CreativeTabs.tabCombat);
}

@SideOnly(Side.CLIENT)
public boolean requiresMultipleRenderPasses()
{
	return true;
}

public ItemStack onEaten(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer)
{
	return par1ItemStack;
}

/**
 * How long it takes to use or consume an item
 */
public int getMaxItemUseDuration(ItemStack par1ItemStack)
{
	return 72000;
}

/**
 * returns the action that specifies what animation to play when the items is being used
 */
public EnumAction getItemUseAction(ItemStack par1ItemStack)
{
	return EnumAction.none;
}
/**
 * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
 */
public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer)
{

	boolean flag = par1ItemStack.getItemDamage() < 31;

	if (flag)
	{

		EntityLaser entityLaser = new EntityLaser(par2World, par3EntityPlayer, 0, 0, 0);
		entityLaser.setDamage(getLaserDamage(par1ItemStack));
		if(!par3EntityPlayer.capabilities.isCreativeMode){
			par1ItemStack.setItemDamage(par1ItemStack.getItemDamage() + 1);
		}
		//par2World.playSoundAtEntity(par3EntityPlayer, "fire.ignite", 1.0F, -5.0F / (itemRand.nextFloat() * 0.4F + 1.2F));

		if (!par2World.isRemote)
		{
			par2World.spawnEntityInWorld(entityLaser);
		}
	}
	else if(par1ItemStack.getItemDamage() == 32){
		Entity entityFireball =	new EntityLargeFireball(par2World, par3EntityPlayer, (double)(-MathHelper.sin(par3EntityPlayer.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(par3EntityPlayer.rotationPitch / 180.0F * (float)Math.PI)),
				(double)(-MathHelper.sin(par3EntityPlayer.rotationPitch / 180.0F * (float)Math.PI)),
				(double)(MathHelper.cos(par3EntityPlayer.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(par3EntityPlayer.rotationPitch / 180.0F * (float)Math.PI)));
		if(!par2World.isRemote){
			par2World.spawnEntityInWorld(entityFireball);
		}
	}

	par3EntityPlayer.setItemInUse(par1ItemStack, this.getMaxItemUseDuration(par1ItemStack));

	return par1ItemStack;
}

public int getLaserDamage(ItemStack itemStack){
	int var1 = itemStack.getItemDamage();
	int var2;
	if((int)(var1 /  == 0){
		var2 = 6;
	}
	else if((int)(var1 /  == 1){
		var2 = 5;
	}
	else if((int)(var1 /  == 2){
		var2 = 4;
	}
	else{
		var2 = 3;
	}
	return var2;
}

@SideOnly(Side.CLIENT)
@Override
public void registerIcons(IconRegister par1IconRegister)
{
	this.iconArray = new Icon[laserIconNameArray.length];

	for (int i = 0; i < this.iconArray.length; i++)
	{
		this.iconArray[i] = par1IconRegister.registerIcon(laserIconNameArray[i]);
	}
	this.itemIcon = iconArray[0];
}

@SideOnly(Side.CLIENT)
public int getColorFromDamage(int damage){
	if(damage >= 31){
		return 0;
	}
	int red;
	int green;
	if(damage >= 16){
		red = 255;
		green = 255 - damage * 16;
	}
	else{
		green = 255;
		red = damage * 16;
	}
	return 65536 * red + 256 * green;
}

@SideOnly(Side.CLIENT)
public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4){
	par3List.add(EnumChatFormatting.DARK_GRAY + Integer.toString(31 - par1ItemStack.getItemDamage()) + " shots left");
}

@SideOnly(Side.CLIENT)
public int getColorFromItemStack(ItemStack par1ItemStack, int par2)
{
	return par2 == 0 ? 16777215 : this.getColorFromDamage(par1ItemStack.getItemDamage());
}

@SideOnly(Side.CLIENT)
public Icon getIconFromDamageForRenderPass(int damage, int renderpass){
	return renderpass == 0 ? this.iconArray[0] : this.iconArray[1];
}
}

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.



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • rp.crazyheal.xyz mods  
    • I'm developing a dimension, but it's kinda resource intensive so some times during player teleporting it lags behind making the player phase down into the void, so im trying to implement some kind of pregeneration to force the game loading a small set of chunks in the are the player will teleport to. Some of the things i've tried like using ServerLevel and ServerChunkCache methods like getChunk() dont actually trigger chunk generation if the chunk isn't already on persistent storage (already generated) or placing tickets, but that doesn't work either. Ideally i should be able to check when the task has ended too. I've peeked around some pregen engines, but they're too complex for my current understanding of the system of which I have just a basic understanding (how ServerLevel ,ServerChunkCache  and ChunkMap work) of. Any tips or other classes I should be looking into to understand how to do this correctly?
    • https://mclo.gs/4UC49Ao
    • Way back in the Forge 1.17 days, work started for adding JPMS (Java Platform Module Support) to ModLauncher and ForgeModLoader. This has been used internally by Forge and some libraries for a while now, but mods (those with mods.toml specifically) have not been able to take advantage of it. As of Forge 1.21.1 and 1.21.3, this is now possible!   What is JPMS and what does it mean for modders? JPMS is the Java Platform Module System, introduced in Java 9. It allows you to define modules, which are collections of packages and resources that can be exported or hidden from other modules. This allows for much more fine-tuned control over visibility, cleaner syntax for service declarations and support for sealed types across packages. For example, you might have a mod with a module called `com.example.mod` that exports `com.example.mod.api` and `com.example.mod.impl` to other mods, but hides `com.example.mod.internal` from them. This would allow you to have a clean API for other mods to use, while keeping your internal implementation details hidden from IDE hints, helping prevent accidental usage of internals that might break without prior notice. This is particularly useful if you'd like to use public records with module-private constructors or partially module-private record components, as you can create a sealed interface that only your record implements, having the interface be exported and the record hidden. It's also nice for declaring and using services, as you'll get compile-time errors from the Java compiler for typos and the like, rather than deferring to runtime errors. In more advanced cases, you can also have public methods that are only accessible to specific other modules -- handy if you want internal interactions between multiple of your own mods.   How do I bypass it? We understand there may be drama in implementing a system that prevents mods from accessing each other's internals when necessary (like when a mod is abandoned or you need to fix a compat issue) -- after all, we are already modding a game that doesn't have explicit support for Java mods yet. We have already thought of this and are offering APIs from day one to selectively bypass module restrictions. Let me be clear: Forge mods are not required to use JPMS. If you don't want to use it, you don't have to. The default behaviour is to have fully open, fully exported automatic modules. In Java, you can use the `Add-Opens` and `Add-Exports` manifest attributes to selectively bypass module restrictions of other mods at launch time, and we've added explicit support for these when loading your Forge mods. At compile-time, you can use existing solutions such as the extra-java-module-info Gradle plugin to deal with non-modular dependencies and add extra opens and exports to other modules. Here's an example on how to make the internal package `com.example.examplemod.internal` open to your mod in your build.gradle: tasks.named('jar', Jar) { manifest { attributes([ 'Add-Opens' : 'com.example.examplemod/com.example.examplemod.internal' 'Specification-Title' : mod_id, 'Specification-Vendor' : mod_authors // (...) ]) } } With the above in your mod's jar manifest, you can now reflectively access the classes inside that internal package. Multiple entries are separated with a space, as per Java's official spec. You can also use Add-Exports to directly call without reflection, however you'd need to use the Gradle plugin mentioned earlier to be able to compile. The syntax for Add-Exports is the same as Add-Opens, and instructions for the compile-time step with the Gradle plugin are detailed later in this post. Remember to prefer the opens and exports keywords inside module-info.java for sources you control. The Add-Opens/Add-Exports attributes are only intended for forcing open other mods.   What else is new with module support? Previously, the runtime module name was always forced to the first mod ID in your `mods.toml` file and all packages were forced fully open and exported. Module names are now distinguished from mod IDs, meaning the module name in your module-info.java can be different from the mod ID in your `mods.toml`. This allows you to have a more descriptive module name that doesn't have to be the same as your mod ID, however we strongly recommend including your mod ID as part of your module name to aid troubleshooting. The `Automatic-Module-Name` manifest attribute is now also honoured, allowing you to specify a module name for your mod without needing to create a `module-info.java` file. This is particularly useful for mods that don't care about JPMS features but want to have a more descriptive module name and easier integration with other mods that do use JPMS.   How do I use it? The first step is to create a `module-info.java` file in your mod's source directory. This file should be in the same package as your main mod class, and should look something like this: open module com.example.examplemod { requires net.minecraftforge.eventbus; requires net.minecraftforge.fmlcore; requires net.minecraftforge.forge; requires net.minecraftforge.javafmlmod; requires net.minecraftforge.mergetool.api; requires org.slf4j; requires logging; } For now, we're leaving the whole module open to reflection, which is a good starting point. When we know we want to close something off, we can remove the open modifier from the module and open or export individual packages instead. Remember that you need to be open to Forge (module name net.minecraftforge.forge), otherwise it can't call your mod's constructor. Next is fixing modules in Gradle. While Forge and Java support modules properly, Gradle does not put automatic modules on the module path by default, meaning that the logging module (from com.mojang:logging) is not found. To fix this, add the Gradle plugin and add a compile-time module definition for that Mojang library: plugins { // (...) id 'org.gradlex.extra-java-module-info' version "1.9" } // (...) extraJavaModuleInfo { failOnMissingModuleInfo = false automaticModule("com.mojang:logging", "logging") } The automatic module override specified in your build.gradle should match the runtime one to avoid errors. You can do the same for any library or mod dependency that is missing either a module-info or explicit Automatic-Module-Name, however be aware that you may need to update your mod once said library adds one. That's all you need to get started with module support in your mods. You can learn more about modules and how to use them at dev.java.
    • Faire la mise à jour grâce à ce lien m'a aider personnellement, merci à @Paint_Ninja. https://www.amd.com/en/support 
  • Topics

×
×
  • Create New...

Important Information

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