How to create mod for minecraft
How to create mod for minecraft
Minecraft: Bedrock Edition Creator Documentation
Learn how to mod Minecraft with Add-Ons. Create skins, design unique experiences, discover the latest features, and develop your skills as a Minecraft creator.
Physically-Based Rendering
Installing Add-Ons in Minecraft: Bedrock Edition
A Redstone Guide
Experimental Features in Minecraft: Bedrock Edition
GameTest Reference Documentation
Differences Between Minecraft Bedrock Edition and Minecraft Java Edition
Building Custom Content
Whether you are creating first Add-On or your one-hundredth, there is content for all types of creators to help you on your journey!
Getting Started with Add-On Development
Working with Add-Ons in Minecraft: Bedrock Edition is easy! Learn how to get started
JSON Reference Documentation
Discover the different features and components used within Minecraft
Getting Started with Minecraft Entity Wizard
Rapidly design, build and deploy a brand new Entity with the new Minecraft Entity Wizard Tool
Discover what you can Create
Building new Add-Ons or want to learning about new Features? The Creator Documentation provides a collection of written content to assist creators.
Add-On Pack Tutorials
Learn how Add-Ons are used to bring custom content into Minecraft
Build a «Complete the Monument» world with Commands
Commands are a powerful way to add logic into your experiences.
Adding new Minecraft Entities
Learn how to create and implement your own custom entities.
Adding NPCs
Populate your world with interactive characters to create unique narrative experiences.
Loot and Trading Tables
Discover how Tables allow creators to add items to the world in a wide variety of ways.
Working with Chunker
Utilize Chunker to convert your existing Minecraft: Java Edition worlds to Minecraft: Bedrock Edition
References
Learn how content works with Reference documentation and how GameTest can empower your workflow.
Using GameTest
Learn how the new GameTest Frameworks can speed up your development time.
Reference Documentation
Need a hand creating your content? View the reference documentation to see how things work in-game.
Common Schema Documentation
See how Schemas are used to validate JSON files in Minecraft: Bedrock Edition
Tools and Vanilla Packs
Get started with some of the most commonly used tools for creating content.
Minecraft Modding#
Хотите создать мод для Minecraft? Добавить в игру что-то свое: блок, сущность или целое измерение?
На этом сайте вы найдете интересный, понятный и подробный учебник по созданию собственных модов для Minecraft.
Вы думаете это сложно? На самом деле нет (с помощью этого учебника)
С чего начать?#
Первый и абсолютно необходимый навык для создания модов — знание основ программирование и Java.
Переменная, объект, класс, метод — все эти слова должны быть вам достаточно хорошо знакомы. Если вы не знаете, что это, то вам необходимо пройти самые основы языка Java. Сделать это можно, например, по этим урокам.
Теперь поговорим об API.
API — набор инструментов для упрощения работы с программой (в нашем случае, с Minecraft).
К сожалению, никакого встроенного API для создания модов у Minecraft нет.
Minecraft не поддерживает моды!
Однако, исходный код игры можно получить, и многие разработчики стали разрабатывать свои неофициальные API: Forge, Sponge и так далее. О Forge вы наверняка не раз слышали. Это самое популярное на сегодня API для создания модов.
Поэтому у вас есть выбор.
Писать моды с помощью API#
Это будет проще. Но запускаться ваши моды смогут только на клиенте с заранее установленным API. Моды, написанные с помощью Forge пойдут только на Minecraft, где предварительно установлен Forge.
Большинство всех Minecraft модов написаны при помощи Forge API.
Плюсы
Минусы
Писать моды без помощи API#
Это несколько сложнее, так как потребует от вас глубокого понимания внутреннего устройства работы Minecraft. При написании модов без использования API вы напрямую редактируете исходный код игры. Получается, что вы словно пишете свой собственный Minecraft (или новую его версию), и никакие другие моды работать вместе с вашим скорее всего не будут.
Плюсы
Минусы
Что выбрать?#
В большинстве случаев рекомендуется писать моды при помощи Forge API. Он сейчас наиболее популярен и является практически стандартом.
Большинство модов и уроков по их созданию написано с помощью этого API. Forge настолько распространен, что частенько под созданием модов для Minecraft понимается именно их создание с помощью Forge API.
У меня вопрос/проблема!#
Если что-то не работает, но должно, или (что еще хуже), что-то работает, но не должно, смело обращайтесь на форум за помощью.
Кстати, там можно не только просить о помощи, но еще и общаться с другими создателями модов, обмениваться опытом и рекламировать свои моды!
Как поделиться с другом?#
Вы можете просто скинуть ссылку на статью. Однако, статьи на данном сайте порой достигают внушительных размеров. В таком случае, можно поделиться ссылкой на конкретный раздел статьи.
Разделы статьи разделяются заголовками. Наведите на заголовок курсор мышки. Справа от него появится значок ссылки. Нажмите на него правой кнопкой и выберите пункт «Копировать адрес ссылки».
Вклад в учебник#
Вы можете вносить правки в существующие статьи, добавлять свои собственные, а также предлагать идеи для новых статей. Сделать это очень просто. Весь процесс полностью автоматизирован. Подробные инструкции вы можете найти на вики по работе с сайтом.
О сайте#
На просторах интернета достаточно много штучных учебников под какие-то конкретные Minecraft версии. Получается, что нет единого источника информации, который поддерживается сообществом, а не единственным автором.
Здесь мы реализуем другой подход.
Сайт работает на статическом генераторе MkDocs с темой Material. Такой подход позволяет не возиться с исходниками сайта, а писать статьи в удобной markdown разметке, которая автоматически собирается в готовый и красивый сайт.
This tutorial will guide you through the process of decompiling the Minecraft source code and editing particular sections of code to create your very own Minecraft mod. In fact it’s not as hard as you might think to create your own Minecraft mod.
It’s recommended that you have some programming experience, but it’s not essential. Most people find it easy to look up Java commands online and enjoy the challenge of learning something new.
Java what.
Don’t let all that programming jargon put you off, Minecraft is actually really well structured making it easy to make modifications.
Applications you’ll need to edit Minecraft source code
Before you can create a mod, you’ll need to download the following applications:
1. Java SDK
The development kit that lets you compile Java code into executable programs.
Java SDK
2. MCP o The Minecraft Coder Pack
This is an awesome pack that contains a selection of folders and batch files to help you decompile java code, obfuscate code and run mods in a test environment. You’ve got no chance without this!
Minecraft Coder Pack
Step by step setup
1. Install the Java SDK (accept the defaults)
2. Install MCP, we recommend choosing C:MCP as your installation folder
3. Install Notepad++ (again accept the defaults)
4. Create an environment PATH.
Just right click on My Computer and click Properties. Go to the Environment Variables section. Scroll down the list of System Variables and edit the PATH variable. Add a semi colon at the end and paste the full path to the bin folder of the Java SDK e.g.
5. Copy the Minecraft bin and resources folders from your Minecraft installation folder into the jars folder of the MCP installation.
Decompiling the Minecraft source code
If you’ve ever had a dig around the minecraft.jar file you’ll have seen a tonne of Java class files. It’s no good opening these files up and attempting to change a few things because the code is compiled and obfuscated. Its just doesn’t make any sense, even in coding terms! And that’s the point of obfuscation, it’s supposed to be compact and smaller in size.
To be able to view the original Minecraft source code you’ll need to turn to our friend MCP and decompile it using their pre-built batch files.
The batch file (.bat) we’re looking for is called decompile.bat and it’s located in the root of the MCP installation folder. Just double click it to start running.
Ok, now we’ve got the full original Minecraft source code! Its saved in the MCPsources folder. E.g.
If you open the src folder, you’ll notice that all the original Minecraft class files are fully readable and the code actually makes some sense.
Editing a Minecraft class file
Ok, so you’ve got all the original source code..now what?
Now the fun begins, all the Minecraft class files are named appropriately. For example, we have an EntitySlime.java class that controls the Slime mod creature. It’s got methods to control the mobs texture, the sound to play when it gets hurt and like other mobs the onUpdate method controls what the mob does on each update.
Just open Notepad++ and drag and drop the EntitySlime.java file onto the notepad text editor. It will look something like this:
In this example, we’re going to just change the texture that the Slime mob uses (it’s a good example if you wanted to copy the Slime mob, create a new minecraft mob and also use your own texture).
Ok, so just type into the text editor and change the texture. In this example, we’ll just change it to use the cow texture because we’re not going to create a whole new texture.
Recompiling the source code
Now that you’ve made your change its time to recompile the code. Just run the recompile.bat file and the code will be compiled again.
If there are any errors during compilation (if you have any syntax errors i.e. your coding is dodgy) you can find these in the MCPlogs folder in the minecraft_compile.log file.
If there are errors, you’ll need to correct your mistakes before you can test your changes. Go back and review the code changes you made, did you type something by mistake?
Testing the new changes
After the codes compiled, you can run the new Minecraft code using the MCP file called test_game.bat. Just double click the file and Minecraft will run as usual.
Obfuscating your changes
If you want to distribute your changes to other Minecraft players and post them on the Minecraft Forum you’ll need to perform a few more steps.
2. Run the reobf.bat file by double clicking it (its in the root of the mcp folder).
3. Your changed classes will be saved in the MCPfinal_outminecraft
4. These will look like the obfuscated files you find in the minecraft.jar file e.g. qm.class
5. These classes are ready to distribute as a new mod..congratulations!!
Создание модификаций с помощью Forge/1.7+
Здесь находятся инструкции по созданию модификаций, работающие для версии 1.7+
Содержание
Подготовка среды и настройка [ ]
Сначала подготовим среду для работы с кодом Minecraft.
Forge [ ]
Собственно, для создания модификаций нужен Forge. Скачать его можно здесь с пометкой Mdk или с пометкой Src (для версий 1.8/1.7). Теперь создайте любую папку там, где вам удобно (в примере это D:\MCModding ), в ней будет находиться Forge и модификация. В эту папку распакуйте содержимое архива с Forge. Вы увидите следующее:
С 15 января 2020 года Maven больше не поддерживает протокол HTTP и требует использовать HTTPS, поэтому для создание модификаций под версию 1.7.10 необходимо в файле gradle/wrapper/gradle-wrapper.properties изменить значение параметра distributionUrl :
Среда разработки [ ]
Теперь нам нужно установить Forge, который при установке также произведёт декомпиляцию и деобфускацию кода Minecraft, чтобы сразу можно было начать создание модификации. Для этого необходимо установить Java Development Kit (JDK), скачав с официального сайта Oracle. При этом JDK должен быть одной версии с Java(JRE)
Первая предпочтительней, так как в отличие от второй команды, подготавливает рабочее пространство с возможностью просмотра исходного кода Minecraft во время разработки. То есть вы всегда сможете посмотреть, как работает генерация мира, анимация движений, применение эффектов и т. д. Таким образом можно создавать модификации, не опираясь на руководства, которых может и не быть на конкретную цель.
Если вы являетесь пользователем операционной системы Linux, нужно прописать следующие строки в терминале:
Выполнение команды займёт какое-то время, после чего должно появиться сообщение рода Build Successful.
Пример результата выполнения команды: [1]
gradlew.bat setupDecompWorkspace eclipse
Если же появляется какая-либо ошибка:
Настройка Eclipse [ ]
Нужно настроить Eclipse для работы с Minecraft. Первым делом зайдите в него. Он предложит выбрать рабочую директорию (Workspace). Введите туда путь к папке «eclipse» в папке (Путь к папке должен содержать только английские буквы), куда вы распаковали содержимое Forge и поставьте галочку для того чтоб окно больше не появлялось. В примере это «D:\MCModding\eclipse». Если всё прошло успешно, то слева в Eclipse вы увидите раскрывающееся меню Minecraft, а снизу не увидите красных ошибок.
Интерфейс Eclipse после правильной установки.
Настройка IntelliJ IDEA [ ]
Если вместо Eclipse Вы решили использовать IntelliJ IDEA, то после того как вы установите ее, в стартовом окне в правом нижнем углу нажмите на кнопку «Configure», откройте вкладку «Project Defaults» и выберите пункт «Project Structure» или в главном меню нажмите комбинацию клавиш (Ctrl+Alt+Shift+S).
Стартовая страница IntelliJ IDEA
В открывшемся окне нажмите на красную надпись «No SDK», для контекстного меню и выберите пункт с вашей версией JDK. (Если же в меню нет вашей версии JDK нажмите «Add SDK» и укажите путь. В нашем случае это C:\Program Files\Java\jdk1.8.0_241 )
После этого можно воспользоваться двумя способами:
Первый способ: [ ]
После того, как Forge скомпилирован и установлен, необходимо запустить IDEA, и в появившемся окне нажать ‘Import Project’. После чего выбираем в папке «D:\MCModding» файл build.gradle. В появившемся окне Вам предложат выбрать способ компиляции (рекомендуется оставить значение Use default gradle wrapper.) В строчке ниже выберите Ваш JAVA_HOME. В пункте «Формат проекта» нужно обязательно выбрать «.ipr (file based)». В противном случае, придётся подключать все библиотеки и настраивать запуск самостоятельно. После всего этого нажмите OK. Ждите, пока сборка скомпилируется.
Второй способ: [ ]
После того, как вы распаковали файлы в «D:\MCModding», сразу запускайте IntelliJ IDEA. В появившемся окне нажать ‘Import Project’. После чего выбираем в папке «D:\MCModding» файл build.gradle.
Если IDEA указывает на старую версию Gradle, нужно обновить ее на более новую. Для этого запустите консоль с директорией к папке с Forge (щелкните ⇧ Shift + ПКМ по папке с Forge > Открыть консоль команд) и выполните следующую команду:
Список всех версий можно посмотреть на официальном сайте.
Потребуется подождать пару минут, пока среда разработки полностью все выполнит и импортирует. После завершения процесса откройте меню «View» в верхней части экрана и выберите пункты «Tools Windows > Gradle». У вас откроется окно с Gradle задачами. Переходим в раздел Tasks > forgegradle.
Готово. Мы проделали все то же самое, что и в первом способе, только без использования консоли, а это может быть большим плюсом для новичков.
Запуск [ ]
После выполнения выше перечисленных действий, в верхней части экрана перейдите в раздел «Run» и выберите пункт «Run configurations». По очереди выберите «Minecraft Client» и «Minecraft Server» и уже в правой части окна, в раскрывающемся списке «Use classpath of module» выберите тот пункт, который заканчивается на _main. Теперь вы можете запустить клиент или сервер и удостовериться, что все работает.
Поздравляем! Вы успешно настроили среду для того, чтобы начать писать модификации при помощи нее.
nornagon / 1-intro.md
How to make a Minecraft mod
Minecraft mods, especially mods which change the client, are by and large written with Forge. If you visit their website, you’ll be greeted abruptly by a mysterious message at the top of an SMF forum, with no clear path towards actually. making a mod. I’m documenting here the steps I went through to get started, in the hopes of helping the next person have an easier time of it.
I’ll be using Scala for this guide, but it should be fairly easy to adapt these instructions to any JVM language (e.g. clojure or if you’re feeling masochistic, Java). I’m also developing on OS X, so some of the commands will be a little different if you’re on Linux or Windows. I’m assuming you have some proficiency with your operating system, so I won’t go into details about how to adapt those commands to your system.
Minecraft doesn’t have an official mod API (despite early promises), so all mods are built off a decompiled version of the source code called Mod Coder Pack, maintained by. I have no idea who, possibly this guy who appears to work at Mojang i.e. Microsoft but still hosts files on Mediafire? MCP is essentially a set of scripts that takes the official Minecraft jar files, decompiles them, and renames all the obfuscated variables and classes. Mojang seems to be fine with this.
Forge is built on top of MCP—it takes the decompiled and deobfuscated source, then tweaks it a bunch, adding hooks in various places that your mod can attach itself to through an extensive set of source code patches. Forge is Minecraft with a mod API.
First up you’re going to want to fetch the latest Forge MDK from http://files.minecraftforge.net/, something like this:
This contains a template project that uses gradle as a build system, hooking into ForgeGradle for its dirty work (decompiling and deobfuscating Minecraft, applying various patches, and so on). To get this going, you’ll want to unzip the template into a new directory
This will dump a bunch of files into the current directory, something like this:
Great! That’s all the stuff we need. Because I want to write my mod in Scala, I’m going to open up the build.gradle and add this line before I do anything else:
And then we want to ask gradle to pull down all the minecraft stuff it needs and do its deobfuscation magic:
This downloads minecraft, decompiles it, deobfuscates the decompiled source, applies a bunch of patches, recompiles everything, and stores it all in
/.gradle/caches/minecraft (so it’s shared between projects—not editable!)
On the shoulders of giants
There are many, many other modding tutorials and talented programmers that I’ve drawn from in writing this series. I’m particularly indebted to:
If this tutorial is at all useful, it is because these others have come before me and shared their wisdom.
Setting up an IDE
I really like using IntelliJ for making Minecraft mods, because it makes it super easy to browse through the deobfuscated Minecraft source code, which is often the only way to figure out how anything works. Fortunately it’s super easy to set up IntelliJ with Forge.
Just hit the ‘Import Project’ button in IntelliJ.
. and select the build.gradle file in your mod directory. Hit ‘OK’ and you’re in!
Importing the project doesn’t automatically create any run configurations, but ForgeGradle comes with a little helper to do that for IntelliJ. Running
will create ‘Run Client’ and ‘Run Server’ run configurations, so booting the client will be as simple as hitting Ctrl+R.
Time for some Scala
It’s SUPER CRITICAL to add the modLanguage = «scala» argument to the @Mod annotation, or you’ll get funky error messages about MyMod. not being defined, like this:
See here for the code in Forge which needs this annotation.
Anyway, you should now be running the simplest possible Scala-based Minecraft mod. Congrats!
The fundamental elements of Minecraft are blocks, items and entities. Blocks are parts of the world, like dirt and obsidian. Items are things that go in your inventory like a sword or a book. Sometimes an item represents a block, like when you have a dirt block in your inventory. And lastly, entities are things that move, like chickens and players.
Blocks form a 3D grid, with X and Z forming the horizontal plane, and Y the vertical axis. Internally, the infinite world is divided into chunks, each 16 blocks to a side and 256 blocks tall. Chunks can be individually loaded and unloaded by the server, and when you fly around the world, the server will send you chunks one by one.
Enough talk. How do I make a block??
We’ll put some more stuff in there later, but for now that’s all we need. We extend from Block and pass Material.ground to its constructor. The Material defines a few basic properties of a block, such as whether or not it’s solid, opaque, burnable, and so on. Browse the Minecraft source starting from net.minecraft.block.material.Material for examples of other materials and their use.
Next up we’ll make an instance of BlockCool and register it with the GameRegistry to give it an ID. Add a preInit event handler to MyMod (the name of the function isn’t important; Forge does reflection magic and looks at the type of the event argument):
And that’s all you need! If you hit run and open the creative inventory, you’ll see something like this:
That beautiful purple and black thing is our baby! Go ahead and plop one down in the world.
Just one thing though. I didn’t actually want it to be black and purple and do nothing.
Models and textures
Let’s solve the ‘not black and purple’ problem first, by way of a blockstates definition file. There are a bunch of different ways to affect the way a block is rendered (up to and including completely custom OpenGL code), but for this relatively normal block the easiest thing for us will be to use the model system built into vanilla Minecraft.
BlockStates and variants
It still looks all dumb and black and purple in our hotbar though, and anyway we don’t want it to look like lapis at all. To fix those issues, we’re going to need to make a custom model.
This defines an item model, which tells Minecraft how to render the item when it’s in our inventory, and when it’s in the world as an item (for example, in the player’s hand, or lying on the floor).
To hook it up so that Minecraft knows to render the item using this item model when it’s in your inventory, add this snippet to the preInit function, after the call to registerBlock() :
Begone, vile magenta! I banish ye forever.
Aside: vanilla assets
It’s super helpful to peek at the vanilla Minecraft assets to see how to structure your own. You can unzip the Minecraft JAR file (which ForgeGradle kindly downloaded for you) to browse them easily. For example:
wherein you will find all the vanilla blockstate definitions, textures and models.
I copied the item model definition from the vanilla lapis block item file, which you can see at vanilla-assets/assets/minecraft/models/item/lapis_block.json if you unzip the vanilla assets (see below).
To banish the lapis, though, we’ll need to make a new model. We could do all sorts of fancy stuff here, but we’re just going to use the basic ‘cube’ model and change its texture. Baby steps.
Interlude: Client and Server
This is because the dedicated server doesn’t include any of the client-side rendering logic. The server JAR doesn’t contain the ModelResourceLocation class, which we’re using in our preInit function, so when the server tries to initialize our mod, it can’t find that class and crashes.
You might also see annotations on functions like @SideOnly(Side.CLIENT) when browsing other Forge mod code. Forge does horrible things with ClassReader to make those functions only appear on either the annotated side. Use at your peril.
Start by making a new Item subclass, called ItemWheatAndSteel :
Instantiate one and register it with the GameRegistry in preInit (or in registerBlocks if you followed the SidedProxy note above):
Finally, make an item model for it in assets/mymod/models/item (cribbed from vanilla-assets/assets/minecraft/models/item/flint_and_steel.json ):
And register it with the ModelLoader in registerItemModels (or otherwise during the preInit phase):
It doesn’t do anything yet, though. Let’s fix that. Override the onItemUse function in ItemWheatAndSteel like this:
You still have to hoe the ground before planting the wheat, though. It’d be neat if it would automatically hoe the dirt, too. (hint: look at how ItemHoe works.)
Источники информации:
- http://mcmodding.ru/
- http://www.planetminecraft.com/blog/how-to-create-a-minecraft-mod—the-complete-tutorial/
- http://minecraft.fandom.com/ru/wiki/%D0%A1%D0%BE%D0%B7%D0%B4%D0%B0%D0%BD%D0%B8%D0%B5_%D0%BC%D0%BE%D0%B4%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D0%B9_%D1%81_%D0%BF%D0%BE%D0%BC%D0%BE%D1%89%D1%8C%D1%8E_Forge/1.7+
- http://gist.github.com/nornagon/f9ae87c01740db0518b7