banner



Minecraft How to Make a Plugin Server TUTORIAL

Minecraft How to Make a Plugin Server

If y'all have always watched the popular Minecraft YouTuber Dream, y'all have noticed that many of his videos feature Minecraft challenges. In these challenges, he and his friends try to beat the game under odd circumstances. These may include crazy events like raids or swarms of bees spawning frequently. This is all made possible using Minecraft server plugins.

Introduction:

A plugin is actress code you add to your Minecraft server to change the default behavior of the game. In this tutorial, we will go over the basics of coding our own plugins. I am a believer that learning should be enjoyable, and so that is the approach I will take. To do this, we will be learning through activeness, creating plugins you tin can have fun with.

Prerequisites:

For this tutorial, I volition presume that you lot have Minecraft Java Edition installed.

I also look you to have a local server ready for testing.

I have decided to skip over setting up a server so nosotros tin can get directly into coding.

If you have not gear up upward a server, yous can notice the instructions here.

You should go into this tutorial with some knowledge of Java programming.

Ideally, yous should have a solid practical agreement of object-orientated programming.

I suspect that some of you may have lilliputian to no programming experience and are reading out of curiosity. In which case it is still fine to read this tutorial.

I intend this to add value for beginners to inspire them to get into recreational coding. Then they can come back to this tutorial subsequently honing their skills enough to follow forth.

For the more experienced programmer, you will learn the foundations needed to code your own plugins.

Equally a final prerequisite, I recommend you to fork a re-create of this repository. It contains resources to become forth with this article and provides extra data. The resource include the projection setup, the final code, and solutions to homework I will give after on.

Project structure and setup:

Before we begin, information technology's necessary to learn how to fix up our project. For this tutorial, we'll be using a tool for Java projects called Maven. If y'all accept never used Maven before, it is a tool we will use to download some external code we demand.

Our project volition comprise a file called "pom.xml" that will tell Maven to download this lawmaking.

To install Maven on your computer, yous tin discover the instructions here.

To brand the project gear up easier, I recommend using the Intellij IDE. Intellij has a plugin you lot tin can use to generate the projection structure with minimal endeavor.

To install it, become to file > settings > plugins, and search for "Minecraft Evolution".

One time installed, get to File > New > Project… > Minecraft > Spigot Plugin.

From there, you have to choose your group ID and antiquity ID. In example you don't know, the artifact ID is the name of your Plugin, whereas the group ID is a unique ID to say y'all created it. The grouping ID is also used to identify projects of similar artifact IDs.

It usually takes the form of a reverse domain (ex. com.google), so if you have your own website utilize it as the group ID. Otherwise, yous tin use something like me.firstname.lastname, or me.minecraftusername.

Brand sure to carve up words past periods, and that they are all lowercase.

From here, the residuum of the procedure is straightforward.

The IDE then asks you for optional settings like a projection description.

Finally, it will enquire what to call the root binder and where to put it. In case y'all wish to employ some other IDE, refer to the repository linked above to find the basic setup.

The repository will also incorporate extra info nearly the setup you may be interested in. In the end, you should accept a project structure like this:

basic setup

All this, except for the .idea folder and (project name).iml file, are the essential elements we need to get started. For this guide, you can disregard any other folders or files.

Within the main package (in this case: src>chief>java>me>john>amiscaray>minecraftplugindevelopmenttutorialfinalcode), you lot should have a single Coffee file.

That Java file, which is named the aforementioned as the artifact ID, should have the following basic structure:

plugin main class

That file will be the main entry point of our plugin where all the magic starts. For that reason, I will exist referring to information technology as our plugin's master class.

I other important file to talk well-nigh is the plugin.yml file. This file has the basic information virtually our plugin needed for information technology to run.

Coding our first minecraft challenge:

Now that we got everything prepare, this is where the fun begins. We will begin by trying to code our plugin to make stepping on grass blocks trigger explosions.

This idea was inspired by this Minecraft video. Thinking most this characteristic, we would need to detect which block a player steps on whenever they movement. To pull this off, we need to wait for the player to move and execute code to cheque which cake they are on.

We can practice this using the assistance of what is called listeners, that listen for in-game events. To start, we will create a new Coffee form called PlayerMovementListener.

Adjacent, we need to fix up the class to listen for and react to events. To do so, nosotros make the class implement the Listener interface from the org.bukkit.event package.

Maven added this packet into our project that contains lawmaking we demand to build our plugin. Now that we divers our class as a listener, we need to create a method that it will call whenever a actor moves.

This method will be a public void method called onPlayerMove. Every bit an argument, it will take a PlayerMoveEvent object.

Whenever the player moves, our class will receive this object and use it to call our method. To ensure our plugin uses the method as a response to a Role player moving, we add the annotation @EventHandler.

Right now, our code should await exactly like this:

                          parcel              me.john.amiscaray.minecraftplugindevelopmenttutorialfinalcode.eventlisteners;              import              org.bukkit.effect.EventHandler;              import              org.bukkit.event.Listener;              import              org.bukkit.event.player.PlayerMoveEvent;              public              course              PlayerMovementListener              implements              Listener              {              @EventHandler              public              void              onPlayerMove              (PlayerMoveEvent event){              }              }                      

As easy every bit that, nosotros prepare a simple class to listen to the player's movement. Now nosotros need to be able to examine the block the player is standing on and human action accordingly. Inside the effect object our method accepts, we can detect all the data we need to code the behavior nosotros want:

                          @EventHandler              public              void              onPlayerMove              (PlayerMoveEvent outcome){              // Get the actor that just moved                                          Histrion p              =              outcome.              getPlayer              ();              // Become the Cake correct beneath the player                                          Block b              =              p.              getLocation              ().              getBlock              ().              getRelative              (BlockFace.              DOWN              );              }                      

From here, we discover the block that the player is standing on. If the cake is a grass cake, we will trigger an explosion:

                          @EventHandler              public              void              onPlayerMove              (PlayerMoveEvent result){              // Become the player that merely moved                                          Player p              =              event.              getPlayer              ();              // Get the Cake correct below the histrion                                          Block b              =              p.              getLocation              ().              getBlock              ().              getRelative              (BlockFace.              Downwards              );              // Create an explosion of power 5 on the thespian's location                                          if              (b.              getType              ()              ==              Material.              GRASS_BLOCK              ){              World w              =              p.              getWorld              ();              due west.              createExplosion              (p.              getLocation              (),              5);              }              }                      

As a final important step, we demand to brand sure we annals this form to listen for events. Merely because we created this form as a Listener, doesn't mean the server will know to use it. Nosotros achieve this by adding this line of code to the onEnable method of our plugin's chief class:

            getServer().              getPluginManager              ().              registerEvents              (              new              PlayerMovementListener(),              this              );                      

Each time nosotros create a new Listener we have to make sure we add together this line to the onEnable method.

There we go, we have created a fun challenge you can play for yourself. The fact that we can create something this cool with little lawmaking shows the scale of what nosotros can do.

To try information technology out, yous demand to bundle the plugin into a jar file and identify it in the plugins folder of your server.

To package it into a jar file open up upward your command terminal in the root directory of the project. From hither, run the command mvn bundle that volition build a few jar files.

The one nosotros are looking for should exist called (Artifact id)-(version).jar.

Amping up our claiming:

Equally if this wasn't difficult enough, our players want something more to challenge them. Allow's amp this up past making the mobs pack a bit more punch.

To practice and then, we will create and register a Listener with the following method:

                          @EventHandler              public              void              onMobSpawn              (CreatureSpawnEvent event){              LivingEntity entity              =              result.              getEntity              ();              if              (entity              instanceof              Monster){              // Give the Monster full diamond armor.                                          entity.              getEquipment              ().              setBoots              (              new              ItemStack(Material.              DIAMOND_BOOTS              ));              entity.              getEquipment              ().              setChestplate              (              new              ItemStack(Cloth.              DIAMOND_CHESTPLATE              ));              entity.              getEquipment              ().              setHelmet              (              new              ItemStack(Material.              DIAMOND_HELMET              ));              entity.              getEquipment              ().              setLeggings              (              new              ItemStack(Material.              DIAMOND_LEGGINGS              ));              if              (entity.              getType              ()              ==              EntityType.              SKELETON              ){              // Create an enchanted bow and give it to the skeleton.                                          ItemStack bow              =              new              ItemStack(Fabric.              BOW              );              bow.              addEnchantment              (Enchantment.              ARROW_DAMAGE              ,              four);              entity.              getEquipment              ().              setItemInMainHand              (bow);              }              if              (entity.              getType              ()              ==              EntityType.              CREEPER              ){              entity.              setInvisible              (              true              );              }              }              }                      

With that, we gave hostile mobs full diamond armor, made creepers invisible, and gave skeletons power four bows. If that isn't a challenge I don't know what is.

Writing our commencement commands:

Every bit fun as it is, let'southward have a suspension from bullying the users of our plugin. Allow's make them a semi-useful command. If you've e'er found an interesting location, you may have created a cobblestone belfry to marker it.

Sure you could write down the coordinates, just this presents us an opportunity to learn block manipulation.

First, we demand to make sure to ascertain the command we can create. We create the definition of our control in the plugin.yml file:

                          # defining our commands.              commands:              # create a new command called mark-location.              mark-location:              description: create a              50              cake tall cobblestone tower to mark a location              # show to the player how they should call the control. You would also show arguments here.              usage: /<command>                                            # create other names nosotros can telephone call the command by.              aliases: [marker, tower]                      

Next, nosotros need to create a form that will execute the command whenever information technology'southward chosen. This grade must implement the CommandExecutor interface of the org.bukkit.control package. This forces us to implement the onCommand method of that interface.

Whenever someone calls the command, our plugin will call this method as a response.

                          parcel              me.john.amiscaray.minecraftplugindevelopmenttutorialfinalcode.commandexecutors;              import              org.bukkit.command.Control;              import              org.bukkit.command.CommandExecutor;              import              org.bukkit.command.CommandSender;              public              class              TowerCommandExecutor              implements              CommandExecutor              {              @Override              public              boolean              onCommand              (CommandSender sender,              Command command,              String label,              String[]              args)              {              render              false              ;              }              }                      

This onCommand method returns a boolean indicating whether the execution was successful. If unsuccessful, the game will ship the user the value of our usage property.

Now we need to generate the cobblestone belfry next to the histrion that called the command. One thing to note is that commands aren't always chosen by players.

The server owner can call commands from their control line while not existence in the game. This forces us to cheque if the command sender is a actor.

To do this, nosotros would do the following command:

                          @Override              public              boolean              onCommand              (CommandSender sender,              Command control,              String characterization,              String[]              args)              {              if              (sender              instanceof              Actor){              Player p              =              (Actor)              sender;              // Become the location 2 blocks in the x-axis next to the player                                          Location origin              =              p.              getLocation              ().              add              (2,0,0);              // Set fifty blocks on the y-axis of the location to cobblestone                                          for              (              int              i              =              0;              i              <              50;              i++){              origin.              getBlock              ().              setType              (Material.              COBBLESTONE              );              origin.              add              (0,1,0);              }              // Send the player a bulletin about what just occurred                                          p.              sendMessage              (              "Successfully added marker at your location"              );              return              truthful              ;              }              else              {              // Print to the command line that you need to be a thespian to execute this command                                          Organization.              out              .              println              (              "Cannot execute this control on the command line"              );              return              simulated              ;              }              }                      

As a final step, nosotros need to annals this CommandExecutor in the onEnable method. This ensures the game assembly the defined control with our CommandExecutor.

To exercise so, add the following line of code:

            getServer().              getPluginCommand              (              "mark-location"              ).              setExecutor              (              new              TowerCommandExecutor());                      

Our terminal project:

Equally a fun final project, permit's create a command to bully people on our server. We will be creating a command called continuous-wither-spawn. When called this would spawn withers on a set interval and location. Earlier in this guide, we worked with creating responses to events.

We will at present larn to cause things to happen on our ain without it being a response. To brand this happen, we will larn how to create and use a form of type BukkitRunnable.

Before we begin, we demand to give a more than detailed description of the characteristic we are adding. We demand our control to spawn withers on a gear up interval at the world spawn point.

To do this, we demand to be able to become an object representing the world so nosotros may add the withers to it. We can get the world the players are in past using its proper noun.

For the sake of our code'south maintainability, I will be setting the world proper name as a configuration variable.

This allows us to admission it throughout the code without us hard coding it every fourth dimension. As an added benefit, the server possessor can change the configuration variables anytime.

If the server owner wants to modify the name of their earth, our plugin won't break. The server owner can update the configuration variable to alter the world name used in our code.

Plus, this allows anyone to employ our plugin on whatsoever Minecraft globe.

To do this, nosotros add the following config.yml file in the aforementioned directory equally our plugin.yml file:

                          globe-name: (your-world-name)                      

Afterwards, add the post-obit to the onEnable method of your main class:

This creates a copy of the config.yml file and the server admin can access exterior of the plugin'southward jar file. This would then allow them to alter the properties even when the plugin is packaged in a jar.

Now that we got that out of the way, let'due south begin.

As we did before, start we need to ascertain our command in the plugin.yml file.

Next, nosotros have to create our CommandExecutor and register it.

From here, we have to create a class of type BukkitRunnable that volition allow us to accept timed events:

                          parcel              me.john.amiscaray.minecraftplugindevelopmenttutorialfinalcode.runnables;              import              org.bukkit.World;              import              org.bukkit.entity.EntityType;              import              org.bukkit.plugin.Plugin;              import              org.bukkit.scheduler.BukkitRunnable;              public              class              WitherSpawnRunnable              extends              BukkitRunnable              {              individual              final              Plugin plugin;              public              WitherSpawnRunnable              (Plugin plugin)              {              // Get the main class that extends JavaPlugin so we can access config variables.                                          this              .              plugin              =              plugin;              }              @Override              public              void              run              ()              {              // Get the world the players are in.                                          String name              =              plugin.              getConfig              ().              getString              (              "world-name"              );              World w              =              plugin.              getServer              ().              getWorld              (proper noun);              // Spawn a wither at the earth spawn location                                          due west.              spawnEntity              (west.              getSpawnLocation              (),              EntityType.              WITHER              );              }              }                      

Our CommandExecutor will use an instance of this class and call the run method on a given interval:

                          @Override              public              boolean              onCommand              (CommandSender sender,              Command command,              String label,              String[]              args)              {              // If the user gave the correct number of arguments (2 arguments, initial filibuster, spawn delay)                                          if              (args.              length              ==              2){              // Get the initial delay and delay betwixt spawns from the arguments. Must bandage them to exist Longs.                                          Long initialDelay              =              Long.              parseLong              (args[0]);              Long spawnDelay              =              Long.              parseLong              (args[1]);              // Run the BukkitRunnable with the above timing                                          new              WitherSpawnRunnable(plugin).              runTaskTimer              (plugin,              initialDelay,              spawnDelay);              return              truthful              ;              }              return              false              ;              }                      

First we check if the user gave the correct amount of arguments. If they didn't, nosotros will non execute this control. Otherwise, we will start spawning Withers with the given delays.

Note, the delays given are in Minecraft ticks; these are effectually 0.05 seconds.

As unproblematic as that, nosotros have created our command. Yous tin can attempt it by typing in the conversation of your server: /continuous-wither-spawn 0 100. This should spawn a wither instantly, and so spawn another every 5 seconds.

Conclusion:

In this tutorial, you lot have gained a foundational understanding on how of to lawmaking Minecraft plugins. I obviously could not cover everything in this tutorial and left some parts out. Some side by side steps are to research command permissions and to merely play around.

In fact, I have learned virtually of this by experimenting and having fun. I would encourage yous to recollect of cool things you lot desire to build and attempt to build them, with some help from the documentation of course. To help you out I have some homework for you to exam your understanding and to proceed learning.

First, I want yous to improve the wither spawn control. Go far so that the user has the option to spawn withers at a location they choose. So make a command that allows them to stop the withers from spawning.

Lastly, try to brand a plugin that volition detect if emeralds are in a loaded chunk. If and then, add together some visual signs of it in the earth. You tin find my solutions to these challenges in the repository.

My solutions may non exist perfect so if you find a better solution, experience gratis to send a pull request. Happy coding!


Peer Review Contributions by: Linus Muema

DOWNLOAD HERE

Minecraft How to Make a Plugin Server TUTORIAL

Posted by: matthewconiefor.blogspot.com

Related Posts

There is no other posts in this category.
Subscribe Our Newsletter
close