I've got a little experience with Java, but I'm new to modding Minecraft.
I want to write a simple mod that plants a sapling if the sapling item entity is dropped on grass, dirt, etc.
Here's my code as is. There's a lot of functionality that hasn't been implemented, like despawning the entity once a sapling has been placed, etc :
@Mod.EventBusSubscriber(modid=TutorialMod.MOD_ID, bus=Bus.FORGE)
public class SaplingHitsGrass {
private static final CharSequence SAPLING=new StringBuffer("sapling");
@SubscribeEvent
public static void saplingHitsGrass(EntityJoinWorldEvent event) {
if(event.getEntity() instanceof ItemEntity) {
ItemEntity item=(ItemEntity) event.getEntity();
ItemStack stack=item.getItem();
if(stack!=null&&stack.toString().contains(SAPLING)) {
TutorialMod.LOGGER.info(stack.toString());
TutorialMod.LOGGER.info("Passed first Conditional");
while(item.isAlive()) {
if(item.ticksExisted!=0&&item.ticksExisted%600==0&&item.onGround) {
BlockState ground=item.getEntityWorld().getBlockState(item.getPosition().add(0, -1, 0));
if (ground.getBlock().getMaterial(ground).equals(Material.EARTH)) {
item.getEntityWorld().setBlockState(item.getPosition(), Blocks.OAK_SAPLING.getDefaultState());
}
}
}
}
}
}
}
I know that the code executes all the way to "Passed first Conditional", and I've tried like 5 different ways to delay, loop, loop with a counter, etc after that. I haven't tried the code past that, don't know if its correct or not.
1) Should I be using a different event? I don't want to lag up the game by checking every entity every tick, so I decided to use EntityJoinWorldEvent.
2) Is there a better way to verify that the entity is a sapling? I'm currently calling the ItemStack's toString() method and checking if that string contains the CharSequence "sapling". This works, but seems janky at best.
3) I want the item to spawn, wait like 600 ticks, and if it still hasn't been despawned it should try to plant the sapling. This is the biggest problem I'm having so far. I've figured out that its a bad idea to use the wait(long delay) function. The best way that I can figure to solve this is to have a counter int and just increment it every tick. That said, I don't know how to do that.