Detecting when a player leaves a projectile and then removing entity - java

I am building a 1.8.8 Bukkit/Spigot plugin that allows you to ride ender pearls and am stuck at detecting a dismount and removing the pearl. I have tried to catch the event but it doesn’t compile. I need a way to remove the pearl when there is a dismount. Thank you!
package damotheryeeter.general.enderpearlride.events;
import org.bukkit.entity.Player;
import static org.bukkit.Material.ENDER_PEARL;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.inventory.ItemStack;
public class EnderThrowEvent implements Listener {
#EventHandler
public void onThrow(final ProjectileLaunchEvent e) {
if (e.getEntityType().equals(EntityType.ENDER_PEARL)) {
if (!(e.getEntity().getShooter() instanceof Player)) return;
if (((Player) e.getEntity().getShooter()).hasPermission("enderpearlride.ride")) {
e.getEntity().setPassenger((Player) e.getEntity().getShooter());
if (((Player) e.getEntity().getShooter()).hasPermission("enderpearlride.infinite")) {
final Player p = (Player) e.getEntity().getShooter();
final ItemStack[] pearl = {new ItemStack(ENDER_PEARL, 1)};
p.getInventory().addItem(pearl);
}
}
}
}

The code for that is:
#EventHandler
public void onDismount(EntityDismountEvent e) {
if(e.getEntity().getEntityType().equals(EntityType.ENDER_PEARL)) {
e.getEntity().remove();
}
}

Related

Adding Potion Effect when Item is in hand Minecraft Forge 1.16.5

So Basically I have been searching the internet for a way to add potion effects while an item is being held. I have found many results but none really seem to be working. My main issue is that when I get to the adding potion effect it throws errors because I am trying to use a non-static to access an abstract. I tried the #Overide several times but it never seems to work. I still need to register in forge as that is how it updates but adding PlayerEntity does not work when I use #SubscribeEvent
package blitz.weapon.weaponmod;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.client.MainWindow;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerAbilities;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.EffectInstance;
import net.minecraft.potion.Effects;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityDispatcher;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.world.NoteBlockEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.InterModComms;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent;
import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent;
import net.minecraftforge.fml.event.server.FMLServerStartingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.util.Objects;
import java.util.stream.Collectors;
// The value here should match an entry in the META-INF/mods.toml file
#Mod("weaponmod")
public class Weaponmod {
// Directly reference a log4j logger.
private static final Logger LOGGER = LogManager.getLogger();
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, "weaponmod");
public static final RegistryObject<Item> RAINBOW_SWORD = ITEMS.register("rainbow_sword", () ->
new Item(new Item.Properties()
.group(ItemGroup.COMBAT)
.maxStackSize(1)
.maxDamage(13)
));
public Weaponmod() {
// Register the setup method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
// Register the enqueueIMC method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC);
// Register the processIMC method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);
// Register the doClientStuff method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);
// Register ourselves for server and other game events we are interested in
MinecraftForge.EVENT_BUS.register(this);
ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
}
#SubscribeEvent
public void onPlayerTick(TickEvent.PlayerTickEvent event) {
if (event.side.isServer() && event.phase == TickEvent.Phase.START) {
ItemStack stack = event.player.getHeldItemMainhand();
if (stack != null && stack.getItem() !=null) {
if (stack.getItem().equals("1 rainbow_sword")) {
return;
}
}
}
}
private void setup(final FMLCommonSetupEvent event) {
// some preinit code
LOGGER.info("HELLO FROM PREINIT");
LOGGER.info("DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName());
}
private void doClientStuff(final FMLClientSetupEvent event) {
// do something that can only be done on the client
LOGGER.info("Got game settings {}", event.getMinecraftSupplier().get().gameSettings);
}
private void enqueueIMC(final InterModEnqueueEvent event) {
// some example code to dispatch IMC to another mod
InterModComms.sendTo("weaponmod", "helloworld", () -> {
LOGGER.info("Hello world from the MDK");
return "Hello world";
});
}
private void processIMC(final InterModProcessEvent event) {
// some example code to receive and process InterModComms from other mods
LOGGER.info("Got IMC {}", event.getIMCStream().
map(m -> m.getMessageSupplier().get()).
collect(Collectors.toList()));
}
// You can use SubscribeEvent and let the Event Bus discover methods to call
#SubscribeEvent
public void onServerStarting(FMLServerStartingEvent event) {
// do something when the server starts
LOGGER.info("HELLO from server starting");
}
// You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD
// Event bus for receiving Registry Events)
#Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)
public static class RegistryEvents {
#SubscribeEvent
public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) {
// register a new block here
LOGGER.info("HELLO from Register Block");
}
}
}
That is my code for basically my whole mod, can anyone give me any pointers? (Sorry for any mistakes this is my first post)

Why does my config.yml file keep on outputting only zero? bukkit plugin

I have made a plugin that is supposed to track the amount of diamonds you have mined in Minecraft and save it to a config.yml file. But my code doesn't seem to be working and I cant figure out why?
I've already tried +1 in the setConfig args and now I've switched over to this and it still doesn't seem to be working. I also have diamonds predefined in my config.yml file.
package com.raidoxe.BlockPlugin;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
#Override
public void onEnable() {
getLogger().info("Sartu has been enabled :)");
PluginManager pm = getServer().getPluginManager();
SartuListener listener = new SartuListener(this);
pm.registerEvents(listener, this);
this.getConfig().options().copyDefaults(true);
this.saveConfig();
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = (Player) sender;
if (sender instanceof Player) {
String lowerCmd = cmd.getName().toLowerCase();
switch (lowerCmd) {
case "mydiamonds":
int a = this.getConfig().getInt("diamonds."+player.getUniqueId());
player.sendMessage(ChatColor.DARK_PURPLE+"You have mined "+ChatColor.RED+a+ChatColor.AQUA+" Diamonds");
return true;
}
}
return true;
}
------------Listener File-----------
package com.raidoxe.BlockPlugin;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.Plugin;
public class SartuListener implements Listener {
private Plugin plugin = Main.getPlugin(Main.class);
public SartuListener(Main plugin) {
}
#EventHandler
public void blockBreak(BlockBreakEvent event) {
Player player = (Player) event.getPlayer();
Block block = event.getBlock();
Material blockMaterial = block.getType();
if(blockMaterial.equals(Material.DIAMOND_ORE)) {
Bukkit.broadcastMessage(ChatColor.WHITE+player.getDisplayName()+" found a "+ ChatColor.AQUA + ChatColor.BOLD+"Diamond!!!");
int a = plugin.getConfig().getInt("diamonds."+player.getUniqueId());
plugin.getConfig().set("diamonds."+player.getUniqueId(), a++);
plugin.saveConfig();
}
}
when the player does the command /mydiamonds it should print out, "you have mined (a) diamonds". But it always prints out zero, no matter how many diamonds you have mined.
Your code seems to be looking fine except one minor mistake. You say that you've tried +1 in the setConfig, so if this solution does not work for you it's probably a version thing
If a config getInt() returns 0 it can mean two things:
value does not exist (default is returned)
value is actually 0 in the config
Upon testing the value does exist in the config (due to saveConfig(), but is set to 0. So this lead me to the setting method.
The issue is the adding part. You do a++ inside the method, this will increment the number after the method, we want before, switch to ++a. See this post.
if(blockMaterial.equals(Material.DIAMOND_ORE)) {
Bukkit.broadcastMessage(ChatColor.WHITE+player.getDisplayName()+" found a "+ ChatColor.AQUA + ChatColor.BOLD+"Diamond!!!");
int a = plugin.getConfig().getInt("diamonds."+player.getUniqueId());
plugin.getConfig().set("diamonds."+player.getUniqueId(), ++a);
plugin.saveConfig();
}

Player Chat event in minecraft java plugin doesnt do what its suposed to do

So I have coded the following code:
package com.ste999.firstplugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class Main extends JavaPlugin {
public Main() {}
#Override
public void onEnable() {
getLogger().info("Stefan's first plugin enabled");
}
private volatile boolean chatEnabled = true;
#EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event) {
Player pli = event.getPlayer();
if (!chatEnabled) {
if (!pli.hasPermission("ste.chat.bypass")) {
pli.sendMessage("§4Chat is disabled!");
event.setCancelled(true);
//return true;
}
}
}
#Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
{
Player p = (Player)sender;
if (cmd.getName().equalsIgnoreCase("mutechat")) {
chatEnabled = !chatEnabled;
sender.sendMessage(chatEnabled ? "§aUnmuted the chat" : "§aMuted the chat");
return true;
}
return true;
}
#Override
public void onDisable() {
getLogger().info("Stefan's first plugin disabled");
}
}
with the following plugin.yml:
name: Stefans_Helper
main: com.ste999.firstplugin.Main
version: 1.0
load: startup
description: this is my first plugin
commands:
mutechat:
description: mute the chat
usage: /<command>
When I use this plugin in my Minecraft server, it shows up and if I do /mutechat it says Muted the chat en when I do /mutechat again it says Unmuted the chat
What I expect this code to do is when the chat is "Muted" no users can talk, unless they have the ste.chat.bypass permission node.
But a user without op and the ste.chat.bypass can still talk in chat after someone did /mutechat and the chat said Muted the chat.
I've tried putting getServer().getPluginManager().registerEvents(this, this); in the public void onEnable but then I get an error in eclipse that says: The method registerEvents(Listener, Plugin) in the type PluginManager is not applicable for the arguments (Main, Main)
Uhh help pls
Your events class (I seriously recommend a new class for this) needs to implement the Listener interface. Only then can you register it.
So I was able to get the mutechat function with the following code:
package com.ste999.events;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
//import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginManager;
public class Main extends JavaPlugin implements Listener{
public static boolean chatMuted = false;
#Override
public void onEnable()
{
getLogger().info("events tester enabled!");
PluginManager pm = this.getServer().getPluginManager();
pm.registerEvents(this, (this));
}
#Override
public void onDisable()
{
getLogger().info("events tester disabled!");
}
#Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args)
{
Player player = (Player)sender;
if (cmd.getName().equalsIgnoreCase("mutechat")) {
if (player.hasPermission("ste999.chat.mute")) {
if(chatMuted == false) {
Bukkit.broadcastMessage("§aThe chat has been disabled!");
chatMuted = true;
}
else {
if(chatMuted == true) {
Bukkit.broadcastMessage("§aThe chat has been enabled!");
chatMuted = false;
}
}
} else {
if (!player.hasPermission("ste999.chat.mute")) {
player.sendMessage("§4You can't mute the chat silly!");
}
}
}
return false;
}
#EventHandler
public void OnChat(AsyncPlayerChatEvent event)
{
Player pli = event.getPlayer();
if (chatMuted == true) {
if (!pli.hasPermission("ste999.chat.bypass")) {
event.setCancelled(true);
pli.sendMessage("§4The chat has been disabled");
} else {
if (pli.hasPermission("ste999.chat.bypass")) {
event.setCancelled(false);
}
}
}
}
}
I needed to register the events but getServer().getPluginManager().registerEvents(this, this) didn't work for me so I needed to do it the way I did it in the code in onEnable and there where a few other problems

Robot Class and Forge Keybinding

All i want is make a forge mod which presses F3 when i press O
This is 2 class files which i have
KeyBindings.java
package com.example.examplemod;
import cpw.mods.fml.client.registry.ClientRegistry;
import net.minecraft.client.settings.KeyBinding;
public class KeyBindings {
// Declare two KeyBindings, ping and pong
public static KeyBinding ping;
public static void init() {
// Define the "ping" binding, with (unlocalized) name "key.ping" and
// the category with (unlocalized) name "key.categories.mymod" and
// key code 24 ("O", LWJGL constant: Keyboard.KEY_O)
ping = new KeyBinding("key.ping", 24, "key.categories.mymod");
// Register both KeyBindings to the ClientRegistry
ClientRegistry.registerKeyBinding(ping);
}
}
KeyInputHandler.java
package com.example.examplemod;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class KeyInputHandler {
#SubscribeEvent
public void onKeyInput(InputEvent.KeyInputEvent event) {
if(KeyBindings.ping.isPressed())
System.out.println("ping");
try {
Robot r = new Robot();
r.keyPress(KeyEvent.VK_F3);
r.keyRelease(KeyEvent.VK_F3);
} catch (Exception e) {
e.printStackTrace();
}
}
}
When i enter game and press O nothing happens

Error Syntax error on token ";", , expected - Minecraft

I am creating a Minecraft mod, and I am getting the error Syntax error on token ";", , expected on this line
public static Block BasaltSmooth;
Here is the code :
package BitBox.Mods.BetterEgg;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
#Mod(modid = "BitBox's Mod", name = "BitBoxMod", version = "V0.1")
#NetworkMod(clientSideRequired = true, serverSideRequired = false)
public class mainClass {
// Initialization
//tabs
public static Item BitBoxTabIcon;
//items
//blocks
public static Block BasaltSmooth;
BasaltSmooth = new BitBoxBlock(500, Material.rock)
.setHardness(0.5F)
.setUnlocalizedName("Basalt Stone")
.setCreativeTab(CreativeTabs.tabBlock);
public static CreativeTabs bitBoxTab;
#EventHandler
public void load(FMLInitializationEvent event) {
LanguageRegistry.addName(BasaltSmooth, "Basalt Stone");
MinecraftForge.setBlockHarvestLevel(BasaltSmooth, "pickaxe", 0);
GameRegistry.registerBlock(BasaltSmooth, "Basalt Stone");
}
public mainClass() {
}
}
You cant do like this
public static Block BasaltSmooth;
BasaltSmooth = new BitBoxBlock(500, Material.rock).setHardness(0.5F).setUnlocalizedName("Basalt
Stone").setCreativeTab(CreativeTabs.tabBlock);
Do like this
public static Block BasaltSmooth = new BitBoxBlock(500, Material.rock).setHardness(0.5F).setUnlocalizedName("Basalt
Stone").setCreativeTab(CreativeTabs.tabBlock);
Prabhakaran's answer should help you with instantiating the Block correctly, Minecraft can be picky at times. Howerever, another issue is that you should register it in the FML PreInit phase:
class{
create block with properties here.
#EventHandler
public void preInit(FMLPreInitializationEvent event) {
Register block with game here
}
}

Categories

Resources