Как сделать майнкрафт на юнити

от admin

Обзор + Скачать КАК СДЕЛАТЬ СВОЙ MINECRAFT С МУЛЬТИПЛЕЕРОМ НА UNITY?! // СЛИВ АССЕТА – VOXEL PLAY // SOURCE CODE

►Видеокарта: GTX 750ti(2gb)
►Процессор: Intel core i3-2120
►Оперативная память: 4GB
►Микрофон: BM-800
____________
Как создать свой бравл старс:

Как создать свой стандоф 2:

Как создать свой knife hit:

#Snz #SnzGames
#Minecraft
#Unity #UnityAssets

В этом видео я показал как создать Minecraft ( как создать игру ), или же КАК СДЕЛАТЬ СВОЙ MINECRAFT С МУЛЬТИПЛЕЕРОМ НА UNITY ,
( как создать игру Minecraft ), за 5 минут,( как создать игру за 5 минут на юнити,игра за 5 минут ,
( юнити ) , так же ссылку на бесплатный исходник игры я оставил в описании, ( бесплатный исходник ) , ( исходник ). ( бесплатный исходник юнити) ,
меня зовут: снз , снз геймс , snzgames , snz , snz unity ,и на этом канале я сливаю платные исходники игр на юнити БЕСПЛАТНО)
voxel play , unity assets free

Создание Minecraft на Unity3D. Часть первая. Создаем базовый куб с текстурой

Обложка: Создание Minecraft на Unity3D. Часть первая. Создаем базовый куб с текстурой

Мы начинаем серию уроков, ориентированную на то, чтобы научить вас создавать простую Minecraft-подобную игру, а также изучить различные аспекты движка Unity3D. Так как это вводный урок, алгоритмы и структура объектов, представленные в этой серии, не самые эффективные.

Приступаем к разработке

Скачайте последнюю версию Unity3D отсюда.

Скачайте текстуры, которые вам потребуются в процессе разработки проекта, описанного в этом руководстве.

  • Текстуры куба:
    • 16×16;
    • 32×32;
    • 64×64;
    • 128×128;
    • 256×256;
    • 512×512;

    Вы можете использовать любое из предложенных разрешений. Вы также можете скачать оригинал:

    Для начала давайте познакомимся с Unity3D. Когда Вы запустите Unity3D в первый раз, всплывет окно Project Wizard. Вы можете импортировать один из встроенных пакетов Unity. Пакеты — это коллекции различных файлов (кода, моделей, аудио-файлов, текстур и т.д.), которые хранятся в виде иерархической структуры, инкапсулированной в файлы с расширением .unitypackage. Пакеты могут быть экспортированы из любого Unity-проекта. Таким образом можно очень просто переносить различные файлы между проектами, сохраняя их иерархию. Сейчас нам не нужно импортировать какие-либо пакеты.

    1_project_wizard

    Окно Unity Project Wizard

    После того, как вы зададите путь для нового проекта, нажмите кнопку Create, чтобы завершить создание проекта. Если Вы открыли Unity и создали проект заблаговременно, вы всегда можете создать новый проект, нажав FileNew Project, чтобы вызвать окно Project Wizard.

    2_file_newproj

    Создание нового проекта Unity

    Интерфейс Unity разделен на несколько вкладок:

    • Вкладка Project содержит все ресурсы, используемые в игре. Для опрятности рекомендуется, чтобы все файлы проекта находились в папках с соответствующими именами (Materials, Textures, Models, Prefabs и т.д.). Это окно показывает, как файлы хранятся на вашем жестком диске, но очень важно, чтобы любые изменения файлов проекта были сделаны из вкладки Project, а не из Проводника, иначе Вы рискуете необратимо потерять связь между файлами.
    • Вкладка Console отображает полезные отладочные сообщения. Если у вас есть минимальный опыт в программировании, вы, вероятно, знаете, почему именно они полезны.
    • Вкладка Inspector показывает различные компоненты, содержащиеся в объектах из вкладок Hierarchy или Project. Вы можете модифицировать любые значения редактируемых объектов отсюда.
    • Вкладка Hierarchy содержит список названий всех объектов, расположенных на текущей сцене.
    • Вкладка Scene показывает игровой мир с произвольной точки (отличной от точки, в которой расположена главная игровая камера). Вы можете изменить позицию этой камеры с помощью клавиш W, S ,A, D и правой кнопки мыши.
    • Вкладка Game показывает, что происходит, когда вы начинаете игру, с точки зрения игровой камеры. В отличие от вкладки Game, вкладка Scene отображает сетку.

    Вы можете расположить вкладки, как вам удобно, перетащив их мышкой в нужное место.

    3_fullwindow

    Любой объект или скрипт, добавленный в проект, может быть сохранен в файле сцены с расширением .unity. Сцены идентичны игровым уровням. Unity-разработчик может разместить игровые файлы на отдельную сцену, когда это необходимо, и загрузить их во время выполения кода. Любой проект может содержать несколько сцен. Чтобы сохранить текущую сцену, нажмите File → Save Scene / Save Scene as… и наберите название в окне проводника.

    4_savescene

    Сохраните ее в папке Assets — корневой папке Unity-проекта.

    5_savescene2

    Если вы откроете папку Assets во вкладке Project, вы можете обнаружить там только что созданную сцену. Кликните здесь правой клавишей мыши и создайте три новых папки: Code, Materials и Textures, как показано на картинке:

    6_createfolder

    Создание новой папки

    7_folders

    Теперь мы готовы начать! Перетащите текстуры куба и скайбокса в папку Textures.

    8_textures

    Импортированные в проект текстуры куба и скайбокса

    Затем зайдите в папку Materials и создайте четыре материала:

    • SkyboxMaterial,
    • BottomMaterial,
    • SideMaterial,
    • TopMaterial.

    Материалы добавляют цвета на 3D-объекты с помощью программ, называемых шейдерами и обрабатываемых на GPU. Больше информации о материалах Unity и шейдерах вы можете получить здесь. Три материала, которые мы создали, будут применены к сторонам куба, который мы создадим в следующем разделе.

    9_createmat

    Создание нового материала

    10_materials

    Материалы для скайбокса и сторон куба

    Кликните левой кнопкой мыши на BottomMaterial. Во вкладке Inspector кликните по кнопке Select, расположенной в компоненте Texture материала, а затем, во всплывшем окне, выберите текстуру bottom.

    11_material_no_texture

    Обззор материала во вкладке Inspector

    12_picktex

    Выбор компонента текстуры

    Затем выберите соответствующие текстуры для SideMaterial и TopMaterial, как показано на картинке ниже.

    13_voxelmaterials

    Материалы куба с загруженными текстурами

    Если вы хотите, чтобы на заднем плане отображался красивый пейзаж, вы можете добавить скайбокс. Для этих целей мы создали SkyboxMaterial, на который мы наложим шесть оставшихся текстур из папки Textures.

    Нажмите левой кнопкой мыши на SkyboxMaterial. Во вкладке Inspector, рядом с меткой Shader, кликните на выпадающий список и выберите RenderFX → Skybox. Это встроенные в Unity шейдеры, которые имплементируют базовые (модель освещения Блинна-Фонга, рельефное текстурирование, отражения, прозрачность и т.д.) и несколько продвинутых шейдеров, таких как параллакс-эффект. Вы также можете писать свои шейдеры и добавлять их в проект.

    14_skyboxmat

    Выбор шейдера для отрисовки скайбокса

    Далее, по аналогии с материалами сторон куба, описанными выше, нам нужно добавить шесть skybox-текстур в соответствующие места.

    15_skyboxtexturesmat2

    Выбор подходящих текстур скайбокса

    Далее, мы должны добавить скайбокс на нашу сцену. Перейдите в Edit → Render Settings. Во вкладке Inspector, рядом с меткой Skybox Material, нажмите на маленький кружок справа и выберите SkyboxMaterial из материалов проекта.

    16_renderskybox21

    Выбор материала скайбокса в RenderSettings

    Если мы приглядимся, мы можем обнаружить грани skybox-куба. Этого можно избежать с помощью наложения текстур. Когда текстура наложена на другую, пиксели, расположенные на краях текстуры, повторяются, заполняясь цветом краев модели, на которой они расположены. Больше информации о наложении текстур можно получить здесь.

    17_unclamp

    Типичное поведение неналоженных текстур

    Перейдите в папку Textures во вкладке Project, выберите все изображения, в пункте Wrap Mode выберите Clamp из выпадающего списка и нажмите Apply.

    18_clamp

    Установка Wrap Mode для всех текстур проекта

    Создаем куб

    Было бы очень заманчиво использовать встроенный примитив Unity — куб — как основу для кубов Minecraft, и расположить соответствующие текстуры из текстурного атласа на стороны куба, используя UV-преобразования, но в этом руководстве мы будем придерживаться простых методик (с наименьшим количеством внешних ресурсов) и будем использовать отдельные меши для каждой стороны.

    В верхнем левом меню кликните на GameObject → Create Other → Quad. Повторите это действие еще пять раз (нам нужно создать шесть сторон куба).

    19_quads

    Создание граней куба

    Теперь назовите каждую из шести сторон соответствующим именем:

    Top, Bottom, Right, Left, Front, Back.

    Объекты, расположенные на сцене, называются GameObject. Чтобы переименовать GameObject, кликните правой клавишей мыши на нем во вкладке Hierarchy и нажмите Rename.

    20_rename

    Переименование граней куба

    Если вы только начинаете знакомиться с Unity, вам крайне рекомендуется ознакомиться с навигацией в окне Scene и позиционированием GameObject, прежде чем идти дальше.

    После создания игровые объекты будут размещены на сцене случайным образом (на самом деле, новые GameObject расположены в точке текущего расположения камеры). Мы должны расположить все стороны куба. Чтобы выровнять их, во вкладке Hierarchy кликните на каждую сторону и модифицируйте её позицию и вращение во вкладке Inspector таким образом:

    22_pos_rot_faces

    Преобразование значений для каждой грани

    Вуаля! Наш серый куб готов:

    21_faces

    Обычный серый куб

    Если куб не центрирован в окне Scene, дважды кликните на одной из его сторон во вкладке Hierarchy, чтобы выровнять камеру.

    Во вкладке Project зайдите в папку Materials. Чтобы создать красивый пиксельный куб, мы должны переместить следующие материалы:

    • TopMaterial на верхнюю сторону,
    • BottomMaterial на нижнюю сторону,
    • SideMaterial на левую, правую, заднюю и переднюю сторону во вкладке Hierarchy.

    23_dragdrop_mouse

    Применяем материалы к GameObject’ам на сцене

    24_voxel

    Куб с текстурами

    Замечательно! Выглядит, как куб из Minecraft, но сейчас у нас есть шесть разделенных частей, а не автономный GameObject, который мы могли бы разместить на нашей сцене. Мы будем использовать простую систему иерархий Unity, чтобы переместить эти части в один GameObject. Она позволяет любому GameObject стать потомком другого GameObject на сцене с помощью простого перетаскивания объекта-потомка на желаемый объект-родитель. Это чрезвычайно удобно, потому что Transform потомка (позиция, вращение и масштаб объекта) станет относительным родительскому объекту.

    В левом верхнем меню выберите Game Object → Create Empty. Это действие создаст пустой GameObject, который будет содержать только компонент Transform.

    25_createempty

    Создание пустого GameObject

    Кликните правой кнопкой на объекте и переименуйте его:

    26_voxel

    Переименование пустого GameObject

    Кликните левой кнопкой на объекте и измените его позицию на (0,0,0).

    27_position000

    GameObject размещён в центре сцены

    Теперь выберите шесть сторон куба и перетащите их в новый пустой GameObject.

    28_finalvoxel_mouse

    Если вы обнаружили ошибки, как на картинке ниже, учтите, что это обычное явление, когда вы вручную меняете иерархию GameObject. Просто нажмите Clear on Play во вкладке Console, чтобы очистить лог ошибок, когда запускаете игру.

    Name already in use

    If nothing happens, download GitHub Desktop and try again.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching Xcode

    If nothing happens, download Xcode and try again.

    Launching Visual Studio Code

    Your codespace will open once ready.

    There was a problem preparing your codespace, please try again.

    Latest commit

    Git stats

    Files

    Failed to load latest commit information.

    README.md

    This tutorial shows a way to create the most basic game mechanics of Minecraft: blocks that can be broken to drop items and a first person player who can pick up the dropped items.

    • Unity Version 5.1.0f3 Personal
    • MonoDevelop-Unity Version 4.0.1 .
    • OS X Yosimite Version 10.10.3 (14D136)

    Should work the same in Windows just with the usual OS interface differences.

    Table of Contents (TOC)

    Create a 3D project and select the default layout in the editor.

    Click to start a new project. (The following is what you should see when you start Unity. If, on the other hand, you already started Unity and have an existing project open, select New Project. under the File menu.)

    New Project

    Name the project.

    Name the Project

    3D should be highlighted.

    3D Project

    Click the create the project.

    Click to Create the Project

    Select the default layout.

    Defaut Layout

    Basic Objects and Mechanics

    Here we build the ground, the block prefab, and the item drop prefab.

    You can think of the following as a quick and dirty substitute for a layer of bedrock.

    Hierarchy | Create | 3D Object | Plane

    Plane

    In the Hierarchy View , click the Create dropdown, select 3D Object and then Plane .

    Inspector | Transform | Scale ( 16, 1, 16)

    Select the plane Scale the plane

    Scale the plane in the x and z directions for plenty of room to play on. The Inspector shows the components of the game object that is selected in the Hierarchy View , so make sure the Plane game object is selected in the Hierarchy View before modifying the Transform component.

    Inspector | Transform | Position ( 0, -0.5, 0)

    Shift the plane down

    Lower the plane by half a unit. Doing this leaves space for unit cubes centered at y=0 so they will be on top of the plane.

    We will now make a block that disappears when clicked on.

    Making a Block Prefab

    Hierarchy | Create | 3D Object | Cube

    Create a Cube

    Create a Cube game object.

    In the Inspector , rename Cube to Block .

    Select the Cube

    Select the Cube game object in the Hierarchy View first.

    Cube name

    Click on Cube in the field at the very top of the Inspector View .

    Cube renamed to Block

    Change it to Block .

    Note that we can name it whatever we want or even leave it with the default name. We just have to be consistent with what we call it thereafter. Since cubes in Minecraft are called “blocks”, it makes sense to call them that in this project.

    Drag the Block game object from the Hierarchy View into the Assets folder of the Project View .

    Block prefab

    This makes it a “prefab”. Prefabs can be added to the game multiple times resulting in multiple game objects that are clones of the prefab. Then changes to the prefab apply to all of those game objects. This is very useful to avoid having to modify lots of game objects just to make a simple change. Another reason it is useful to make prefabs is because they can be “instantiated” from scripts dynamically at run time. We will eventually want to do this in order to produce a procedurally generated terrain of blocks.

    Drag a few Block prefabs into the scene.

    Scene with some blocks

    In the Inspector for each block, manually assign their position coordinates to be integers and make them all have y=0 in particular.

    Block1 select Block1 position

    Observe that Unity automatically numbers the game objects generated from prefabs.

    Block2 select Block2 position

    Block3 select Block3 position

    Save the Scene and the Project

    File | Save Scene

    Select File and Save Scene .

    Save Scene

    We will only have the one scene, so no need for a very purposeful name. Let’s just name it Scene .

    Now a scene asset named Scene will appear in the Assets folder of the Project View .

    Scene Asset

    File | Save Project

    Select File and Save Project .

    Save Project

    The project already has a name from when we created it, so there will not be a prompt for naming it.

    Adding a Script to the Block Prefab

    In the Assets folder of the Project View , right-click and select Create | C# Script

    Create MineBlock.cs script

    Rename it to MineBlock .

    Newly created MineBlock.cs script

    Its default name is NewBehavior . Just type over that to change it to MineBlock .

    Renamed MineBlock.cs script

    Now double-click the MineBlock C# asset. That will cause the script to be loaded in Mono.

    Mono MineBlock initial script

    There is a Start function and an Update function. They are empty to start with. We could write code in them, but we won’t for now. We can also add other functions. We will add another function soon.

    It is important to realize first and foremost, however, that this script needs to be “attached” to a game object (or multiple game objects). Let’s go ahead and attach it to our block prefab before delving into actual coding in the script.

    Go back to Unity and select the Block prefab.

    Select Block Prefab

    Now click and drag the MineBlock script asset over to the Add Component button in the Inspector View for the Block prefab and drop it there.

    MineBlock Script Drop To Add

    The MineBlock script will be added as a component to the Block prefab.

    MineBlock Script Added

    Note that the Add Component button activates a menu through which we could have added the script as well. (There are usually multiple different ways of accomplishing the same thing.)

    Go back to Mono and add the following OnMouseDown function to the MineBlock script.

    Mineblock Script OnMouseDown Destroy

    Here’s the code for you to copy-and-paste if necessary:

    However, it is recommended that you type the code yourself to help you learn the patterns.

    Save the script in Mono.

    Save the Script

    Go back to Unity and run the game by clicking on the play button.

    1. Save the scene and the project.

    Hide the original Block game object

    In the next section we are going to add a new game object to the scene. To keep the scene view clean in preparation for that, we will now hide the original Block game object that we used to make the Block prefab. Also, eventually, we will be placing multitudes of blocks from a script at run time in some systematic way and will want to remove all of the hand-placed blocks from the initial scene. For now, we will leave the other few blocks that were added to the scene via the prefab just to have something there in the meantime. We do want to hide the original one, though, because it occupies the special origin location that other new game objects will occupy by default. (Alternatively, we could just move it out of the way, but we are going to want to hide it eventually anyway so let’s just do it now.)

    In the Hierarchy View , select the Block game object.

    Select the Block Game Object

    In the Inspector View , uncheck the checkbox next to the game object’s name field.

    Uncheck Checkbox Next to Name Field

    That game object should no longer appear in the scene. It is still listed in the Hierarchy View although dimmed.

    In Minecraft, when a block is “mined” it can drop a resource which appears as a smaller version of the block floating in the space that the original block had occupied. This section shows how to create a dropped block prefab and cause it to be instantiated in place of blocks whenever blocks are destroyed.

    Hierarchy | Create | 3D Object | Cube

    Create a Cube

    Create another Cube game object.

    Rename it DroppedBlock .

    Rename to DroppedBlock

    Inspector | Transform | Scale (0.5,0.5,0.5)

    Scale the Dropped Block

    Make it smaller.

    Inspector | Transform | Rotate (15,0,5)

    Rotate the Dropped Block

    Feel free to adjust the scale and rotation as desired. To make it look like a dropped item, it just needs to be smaller and tilted.

    Make a prefab from the DroppedBlock game object by dragging it into the Assets folder of the Project View .

    DroppedBlock Prefab

    Select the source DroppedBlock Game Object and hide it.

    Select DroppedBlock Game Object Hide DroppedBlock Game Object

    Go to Mono and edit the MineBlock script by adding this line

    before the Start function:

    Script Object for DroppedBlock Prefab

    Go back to Unity and select the Block prefab.

    Select the Block Prefab

    Look at the Inspector View and see the Dropped Block Prefab field in the Mine Block (Script) component.

    DroppedBlockPrefab Field

    That field was put there automatically by the Unity editor after we declared the droppedBlockPrefab variable in the MineBlock script.

    Now drag the DroppedBlock prefab into that Dropped Block Prefab field.

    Dragging DroppedBlockPrefab

    DroppedBlockPrefab Dropped

    This will cause the droppedBlockPrefab variable in the MineBlock script to be initialized to the DroppedBlock prefab when the game runs. It is in this way that our script will have access to that prefab.

    Finally, add this line

    to the OnMouseDown function of the MineBlock script right before the Destroy statement.

    Instantiate On Mouse Down

    This causes the DroppedBlock prefab to be “instantiated” as a game object at the same position as the block that was clicked and with the rotation that we specified in the Inspector for the DroppedBlock prefab.

    Save the script.

    Save the Script

    Go back to Unity and save the scene and project.

    Save Scene Save Project

    Run the Game

    See that when you click a Block game object, a DroppedBlock game object appears in its place.

    Stop the Game

    First Person Character

    This section adds a first person character to the scene so that the player can look around and move around in a way similar to Minecraft.

    Beware: The first person character asset is provided by Unity in the Standard Assets package, so Standard Assets must be installed. If they are not, the Import Package menu in the very first step below will not contain the shown options. In that case, go to the Asset Store :

    Asset Store Under Window Menu

    and download/import Standard Assets from there instead.

    Assets | Import Package | Characters

    Import Package Characters

    If you do not see the shown options in your Import Package menu, see the note above. You will need to install/import them from the Asset Store .

    Click the «None» button to uncheck all of the options.

    Click None to Deselect All

    Click the checkbox next to FirstPersonCharacter .

    Select FirstPersonCharacter

    Now just the FirstPersonCharacter asset is selected.

    FirstPersonCharacter Selected

    Click the Import button.

    Click Import

    Notice the new StandardAssets folder inside your Assets folder of the Project View .

    New StandardAssets Folder

    You will also notice an error message in the Unity status bar. If you click the Console tab next to the Project tab, you will see other messages, too. There are a couple of dependencies that we need to import before we can use the FirstPersonCharacter standard asset.

    Assets | Import Package | CrossPlatformInput

    Import Package CrossPlatformInput

    Click Import

    And now there is a new folder named Editor inside the Assets folder of the Project View .

    New Editor Folder

    Assets | Import Package | Utility

    Import the Utility Package

    Click the Import Button

    No additional new folders will appear at the top level of the Assets folder this time, but you’ll see that the error messages have disappeared now.

    Add and Configure Character

    Under the Assets folder in the Project View , expand StandardAssets , Characters , FirstPersonCharacter , and then select Prefabs .

    FPSController Prefab

    Notice the FPSController prefab. That’s what we are going to use.

    Drag the FPSController prefab into the scene.

    Drag the FPSController into the Scene

    Drop it somewhere near the current camera.

    Dropthe FPSController into the Scene

    Remove the old camera which is called Main Camera .

    Delete the Old Main Camera

    The FPSController prefab comes with its own camera built in.

    Adjust the y coordinate of the FPSController position so that it is completely above the plane, e.g., y=2 .

    Select the FPSController Game Object Adjust Position of FPSController

    It’s okay if it starts higher than the plane. It will fall to the surface when the game begins.

    Save the scene and project.

    Save Scene Save Project

    Run the Game

    Notice that the camera follows the cursor as expected for a first person character. Also, you can use the W A S D keys to make the player walk and the SPACE bar to make it jump.

    Stop the Game

    Adjust the scale of the FPSController to (0.5,0.9,0.5) .

    FPSController Selected Adjust the Scale of the FPSController

    This will make it possible for the character to fit through one block wide and two block high openings (eventually).

    Save Scene Save Project

    The way the player interacts with the scene will be more natural if the cursor is always in the center of the screen (like the crosshairs of Minecraft).

    Select the Assets folder in the Project View and create a new C# Script .

    Create MouseLock Script

    Rename the new script to MouseLock .

    New Script Renaming Script Script Renamed

    Select the FPSController game object.

    Select FPSController Game Object

    Scroll down in the Inspector View until the Add Component button is visible.

    Drag the MouseLock asset onto the Add Component button of the Inspector for the FPSController .

    Add MouseLock Script as Component of FPSController

    Now the Mouse Lock (Script) component should appear in the list of components for the FPSController .

    MouseLock Script Added

    Double-click the MouseLock C# asset in the Project View to open it in Mono.

    Initial MouseLock Script

    Notice that Mono now has two tabs, one for the Mineblock script that we edited previously (and will return to later) and one for the new MouseLock script that we will edit now.

    To lock the mouse cursor when the game begins, put this line

    in the Start function.

    Cursor Lock in Start Function

    To unlock the mouse cursor when the user presses the ESC key, put these lines

    in the Update function.

    Capture ESC in Update Function

    Save the script.

    Save the Script

    Go back to Unity and save the scene and the project.

    Save Scene Save Project

    Run the Game

    If you’re lucky, the mouse cursor will lock in the middle of the Game View until you hit the ESC key.

    Cursor Centered in Game View

    The mouse lock mechanism can be a bit flakey in the Game View . Sometimes it doesn’t work right. To see it work reliably, we might need to build the game as a native application.

    Stop the Game

    In my experience, if the cursor lock doesn’t work the first time the game is run, stopping it and then running it again will make it work, so try running it again at this point. (And then stop it before proceeding.)

    File | Build Settings.

    File | Build Settings.

    From the File menu, select Build Settings. .

    PC, Mac & Linux Standalone .

    Platform

    From the Platform list, select PC, Mac & Linux Standalone .

    Targer Platform

    Select your operating system from the Target Platform menu.

    Click the Build And Run button.

    Click Build And Run

    Name the application something like MakingMinecraft .

    Name the Application

    Save the Application

    Select your desired resolution from the Configuration dialog that pops up.

    Choose Resolution

    Check the Windowed check box.

    Check Windowed

    This will make the application run inside a window rather than in full screen. (Optionally, you can leave that checkbox unchecked to run in full screen mode, but it might be tricky to escape out of the game when it is running that way.)

    Play!

    Click the Play! button and enjoy playing the game as a native application.

    Application Running

    When finished playing, press ESC to unlock the cursor and then close the application.

    Back in Unity, close the Build Settings window.

    Close Build Settings

    When the player runs into a dropped block, the dropped block game object should disappear as the player “picks up” the item.

    Select the DroppedBlock prefab in the Assets folder of the Project View .

    Select the DroppedBlock Prefab

    In the Inspector View , check the Is Trigger check box of the Box Collider component.

    Check the Is Trigger Check Box

    In the Assets folder, create a new C# Script.

    Create New C# Script Asset

    Rename it to PickUp .

    New Script Renaming Renamed

    Select the DroppedBlock prefab again.

    Select the DroppedBlock Prefab

    Drag the PickUp script over to the Add Component button in the Inspector for the DroppedBlock prefab.

    Adding PickUp Script Component to DroppedBlock Prefab

    Then the Pick Up (Script) component should appear in the list of components in the Inspector for the DroppedBlock prefab.

    PickUp Script Added

    Save the scene and project.

    Save Scene Save Project

    Double-click the PickUp script to open it in Mono.

    Double Click the Pickup Script

    Now you will see three tabs in Mono with the one for the PickUp script in front.

    Initial PickUp Script

    Add the following OnTriggerEnter function

    after the Update function like this:

    OnTriggerEnter Function in PickUp Class

    Save the script.

    Save the Script

    Back in Unity, run the game.

    Run the Game

    Click on a block to make it drop a dropped block item and then run your character into the dropped block. It should disappear.

    Stop the Game

    Breaking blocks and collecting dropped items is much more satisfying with sound effects!

    Add Sound Assets.

    Download the following two wav files:

    Save Link As

    Save them in the Assets folder.

    Save in Assets Folder

    Do that with both files: dig_grass1.wav and pop.wav . Then you will see both of those files in the Assets folder on your harddrive.

    Assets Folder Listing

    They will also appear in the Assets folder inside the Unity editor.

    Assets Folder in Unity

    Sound Effect for Mining Blocks

    In the MineBlock script in Mono, add this line

    at the top of the MineBlock class:

    MineSound Variable in MineBlock Class

    Save the MineBlock script in Mono.

    Save the MineBlock Script

    Go back to Unity. Select the Block prefab from the Assets folder and notice the Mine Sound field in the Mine Block (Script) component in the Inspector .

    Mine Sound Field in Mine Block Script Component

    Drag the dig_grass1 asset into that field.

    Adding dig_grass1 Asset to Mine Sound Field dig_grass1 Asset Added to Mine Sound Field

    Go back to Mono and add this line

    inside the OnMouseDown function before the Destroy statement.

    PlayClip

    Save the MineBlock Script

    Go back to Unity and save the scene and project.

    Save Scene Save Project

    Run the Game

    If you have audio on your computer, you should now hear the familiar sound of a dirt block breaking when you click on a block.

    Stop the Game

    Sound Effect for Picking Up Dropped Blocks

    Challenge: As an exercise, see if you can now add the sound effect for picking up dropped blocks without looking at the following instructions.

    In the PickUp script in Mono, add this line

    at the top of the PickUp class:

    PickUp Sound Varialbe in PickUp Class

    Save the PickUp Script

    Back in Unity, select the DroppedBlock prefab and see the Pickup Sound field in the PickUp (Script) component in the Inspector .

    PickUp Sound Field in Script Component

    Drag the pop asset into that field.

    Adding Pop Asset to PickUp Sound Field Pop Asset Added to PickUp Sound Field

    Go back to Mono and add this line

    in the OnTriggerEnter function before the Destroy statement:

    PlayClip

    Save PickUp Script

    Go back to Unity and save the scene and project.

    Save Scene Save Project

    Run the Game

    After breaking a block to make it drop a dropped block, when you run your character into the dropped block you should hear the popping sound of the item being collected.

    Stop the Game

    Balance the Volume of Sound Effects

    The walking/stepping sound effects that come as part of the FPSController may be too loud relative to the sound effects for breaking and picking up blocks. Let’s turn the FPSController sound effects down a little.

    Select the FPSController game object in the Heirarchy View .

    Select FPSController Game Object

    In the Inspector View , adjust the Volume slider in the Audio Source componenent.

    Adjust Volume

    About half volume feels right to me, but adjust to suit yourself.

    Save the scene and project.

    Save Scene Save Project

    Run the Game

    Stop the Game

    If unsatisfied with the volume balance, go back to step 2, otherwise continue to the next section.

    Now that the basic breaking and collecting mechanics are in place, let’s generate an actual terrain rather than a scattering of hand-placed blocks.

    Create a new C# Script called GenTerrain .

    Create GenTerrain C# Script

    Select the Plane game object.

    Select Plane Game Object

    Add the GenTerrain script as a componenet on the Plane game object.

    Adding GenTerrain Script to Plane GenTerrain Script Added to Plane

    Double click the GenTerrain script to open it in Mono.

    Open the GenTerrain Script

    at the top of the GenTerrain class just before the Start function.

    Add Block Variable to GenTerrain Class

    Save the GenTerrain Script

    Go back to Unity and see the Block field in the GenTerrain component in the Inspector for the Plane game object.

    GenTerrain Block Field

    Drag the Block prefab into that field.

    Adding Block Prefab to Block Field Block Prefab Added to Block Field

    Back in Mono, add these lines

    to the Start function in the GenTerrain class:

    GenTerrain Start Function Code

    Save the Script

    Back in Unity, select the FPSController game object

    Select FPSController

    and adjust its Position

    Adjust FPSController Position

    so that the player starts in the middle of the world and up high.

    Delete the manually placed blocks.

    Deleting Manually Placed Blocks Manually Placed Blocks Deleted

    Save the scene and project.

    Save Scene Save Project

    Run the Game

    Stop the Game

    The following list of tasks can be done in any order and independently of the others. They are listed roughly in order of how much time they should probably take.

    Turn Off Shadows

    If you wish, you may turn off shadows for the Block and/or DroppedBlock prefabs.

    In the Mesh Renderer component, you can toggle both whether the object casts shadows and whether the object receives shadows.

    Animate Dropped Blocks

    in the Update function of the PickUp class:

    The first argument transform.position specifies the center of the rotation. The second argument Vector3.up specifies the axis of rotation. The third argument, a multiple of Time.deltaTime specifies the speed of the rotation. Adjust that multiple 100 to suit.

    Add a Material to the Block Prefab

    Right click in the Assets folder and select to Create a Material asset.

    Create a Material

    It will be named New Material by default.

    New Material

    Rename it to BlockMaterial .

    Renamed to BlockMaterial

    Click the white color box toward the top of the Inspector for the BlockMaterial .

    Color Select Box

    Choose a Color

    Close the Color selector.

    Close the Color Selector

    Select the Block prefab in the Assets folder.

    Select the Block Prefab

    Click the little triangle to expand the Materials property of the Mesh Renderer component.

    Expand Mesh Renderer Materials

    See the Element 0 field.

    See the Element 0 Field

    Drag the BlockMaterial asset into that field

    Dropping the BlockMaterial Asset into the Element 0 Field BlockMaterial Dropped in the Element 0 Field

    Save the scene and project.

    Save Scene Save Project

    Run the Game

    The blocks should now appear in whatever color you selected for the material.

    Stop the Game

    Add a Material to the DroppedBlock Prefab

    Exercise: Complete this task on your own. Make the game play the pop.wav sound when the player picks up a dropped block.

    Score Counter / Inventory

    Create | UI | Text

    Create a UI Text Object

    Create a UI Text game object in the Hiearchy View . It will appear as a child of a Canvas object which get automatically created for this purpose.

    Select the UI Text Object

    There is also an EventSystem game object that is created automatically at this point which we will ignore for now.

    Set an Anchor Preset .

    Select the Anchor Preset menu

    Select the Anchor Preset menu in the Inspector for the Text game object.

    Anchor Preset Menu

    Hold down the Alt key. See how the annotations change to signify position.

    Anchor Preset Menu with Alk Key Down

    Select a desired position. I propose the bottom middle since that is where the Minecraft hotbar is displayed.

    Anchor Preset Selected

    Change the contents of the Text field from New Text to 0 .

    Changing The Default Text

    Default Text Changed

    Increase the font size a bit:

    Increase Font Size

    Center the text by clicking the center Alignment button in the Paragraph section.

    Center the Text

    Go to Mono and select the PickUp script tab.

    Select Pickup Script Tab

    Add this using directive

    at the top of the file:

    Using UnityEngine.UI

    This will allow us to access the Text component of the Text game object.

    Add this private static variable declaration

    and this private variable declaration

    at the beginning of the PickUp class:

    Num Collected Vars in PickUp Script

    in the Start function:

    Code to Find Text Object

    Finally, put these lines

    in the OnTriggerEnter function:

    Lines to Update Num Collected

    Save the Script

    Go back to Unity and save the scene and project.

    Save Scene Save Project

    Run the Game

    See the counter increment whenever you pick up a dropped block.

    Stop the Game

    More Elaborate Mouse Lock Mechanism

    We will replace the cursor pointer with crosshairs and allow for relocking after unlocking.

    Replace Cursor Pointer with Crosshairs

    This task involves first making an image of crosshairs. The following instructions are for GIMP, the GNU Image Manipulation Program, which is a free image editing application similar in functionality to Photoshop. Feel free to produce the image in whatever image editing application you prefer or even just find an image of crosshairs online. (The image file format can be PNG or JPG . Maybe it can be other formats, too, but I’m not sure.)

    Run GIMP and create a new image.

    New GIMP Image

    Adjust the size to something fairly small and probably square is best. For the tutorial, we’ll do a 16×16 image.

    Size the New Image

    Click Okay to create the new image.

    Click Okay

    In the zoom dropdown menu select 800%.

    Zoom

    That way we can edit the image pixels easily.

    Zoomed

    Select the Pencil Tool from the Toolbox window.

    Select Pencil Tool

    Make sure that under Tool Options the Mode is Normal and the Brush is 1. Pixel and the Size is 1.00 .

    Draw horizontal and vertical lines for crosshairs.

    Draw Lines

    Maybe decorate them a bit.

    Decorate

    Feel free to draw your crosshairs however you like. They don’t have to look the same as this.

    Make the white background of the crosshairs transparent.

    Make Background Transparent

    Select Color To Alpha. from the Colors menu.

    Click Okay

    It should default to white as the color to convert to Alpha , i.e., make transparent, so just click Okay .

    Transparent

    Export the image to a PNG file.

    Export

    Expand the Select File Type menu.

    Expand File Type Menu

    Expanded, it will show a list of file types to select from:

    Expanded

    Select PNG image .

    Select PNG

    Now name the file crosshairs.png.bytes .

    Name the File

    Select the Assets folder of your project to save it in and then click the Export button.

    A PNG file with a .bytes extension on the file name is very unusual! Unity wants it that way, but GIMP is skeptical. You will need to confirm that you do want to go with that unusual name.

    Confirm Name

    You will be presented with another dialog window containing various options.

    Export Options

    Just click the Export button to accept the defaults.

    Go to Unity and notice the new crosshairs.png asset in the Assets folder.

    New Crosshairs Asset

    Go to the MouseLock script in Mono and add these lines

    at the top of the MouseLock class:

    MouseLock Texture Variables

    Put these lines

    in the Start function of the MouseLock class after the line that sets the cursor lock state:

    MouseLock Load Image

    If you created a crosshairs image that is bigger than 16×16, you’ll need to adjust the numbers for the size of the Texture2D object and the Vector2 argument in the SetCursor function call. The Vector2 object specifies which point inside the image should be used as the cursor point. For a crosshairs shaped cursor it makes sense for it to be in the middle of the cursor image.

    inside the if statement of the Update function after the line that unlocks the cursor:

    MouseLock Reset Cursor

    That sets the cursor back to the default. Vector2.zero means coordinates (0,0) which are at the top left corner of the cursor image which corresponds to the tip of the point of the default cursor.

    Save the Script

    Now go back to Unity and select the FPSController in the Hierarchy View .

    Select FPSController

    Scroll down in the Inspector View for the FPSController and notice the Cross Hairs Raw field in the Mouse Lock (Script) component.

    Drag the crosshairs.png asset into that Cross Hairs Raw field of the Mouse Lock (Script) component.

    Adding Crosshairs to Script Field Crosshairs Added

    Save the scene and project.

    Save Scene Save Project

    Run the Game

    The cursor should change to the crosshairs shape.

    Stop the Game

    You might have to stop and restart the game in order to get it to work. Also, when running the game inside the unity editor, the cursor many not change back from the crosshairs cursor when you press ESC , or at least not until you move the cursor outside of the Game View .

    Mechanism to Relock Cursor After Unlocking

    Mouse click to lock cursor. Add else if clause

    after if statement in the Update function:

    As usual, this might not work flawlessly when running the game in the Unity editor. Try doing a File | Build & Run .

    Outline Blocks on Focus

    We will use the Unity GL graphics library.

    Create a new C# script.

    Create Script

    Call it WireFrame .

    Name it WireFrame

    Attach it to the FirstPersonCharacter game object. The GL functions are typically called from a script attached to the camera, and our camera is in the FirstPersonCharacter . (See the Unity GL documentation for more information)

    Select FPSController Attach WireFrame to FPSController

    Double-click the WireFrame script asset to open it in Mono and add the following lines

    at the top of the class:

    WireFrame Variable Declarations

    The wireMaterial object will be used for draw lines with GL. The targetBlock object will be the block which lines are to be drawn around.

    Save the Script

    Go back to Unity and create a new Material asset.

    New Material

    Name it WireMaterial .

    Name it WireMaterial

    Change it to black.

    Change Material Color to Black

    Select the FirstPersonCharacter object and drag the WireMaterial asset into the corresponding field of the WireFrame script.

    Attach WireMaterial to WireFrame Script

    With the FirstPersonCharacter still selected, drag the Block prefab into the Target Block field of the WireFrame script.

    Attach Block Prefab to WireFrame Script

    Note that this is just temporary. In later steps, we will code the targetBlock to be assigned dynamically at run time based on which block the player is looking at.

    Open the MineBlock script in Mono and add the following line

    at the top of the class:

    MineBlock Variable Declaration

    to the Start function:

    MineBlock Find FPSController

    Add functions OnMouseEnter and OnMouseExit

    at the bottom of the class after the OnMouseDown function:

    MineBlock OnMouseEnter and OnMouseExit

    to the OnMouseEnter function:

    Set TargetBlock

    This assigns the Block game object that the player is pointing at to become the targetBlock in the WireFrame script. Now we need to code the WireFrame script to actually draw a wireframe around that block. (There is a loose end to the mechanism in MineBlock that we will take care of later. If the player looks away from a block but not at another block, the last block the player was looking at will remain highlighted with a wireframe. But let’s not worry about that until the WireFrame script is actually drawing something.)

    Back in the WireFrame script add this function

    at the end of the class:

    WireFrame OnPostRender

    Add these lines

    to the OnPostRender function:

    WireFrame GL Framework

    There are three sets of four lines that need to be drawn around the cube. There is one set of four edges on a cube for each of the three directions in 3D space.

    The way a GL line works is by specifying the starting point and ending point of the line with two consecutive calls to GL.Vertex .

    The four lines in the right to left direction can be specified relative to the targetBlock.transform.position like this:

    The factor of 0.51 is to make the lines hover a slight bit out from the actual edges of the cube (just like in Minecraft, as you may have noticed).

    The four lines going up and down can be specified like this:

    And the four lines along the front to back edges of the cube can be specified like this:

    Replacing each respective TODO in the OnPostRender function with the above lines of code results in this:

    WireFrame Lines

    The if statement checks to be sure targetBlock exists before attempting to wire frame it. This prevents Unity from becoming confused by targetBlock.transform after the player clicks and breaks the block that they are looking at. It doesn’t make sense to access the transform of a game object that no longer exists.

    Finally, let’s tie up the loose end mentioned above. Currently, if the player moves the cursor off of a block and into the sky or plane or something other than another block, that last block that the player was looking at remains highlighted with a wire frame.

    to the top of the MineBlock class:

    MineBlock DrawWireFrame Variable Declaration

    to the Start function:

    Init DrawWireFrame Variable

    Set drawWireFrame to true in OnMouseEnter and set it to false in OnMouseExit .

    DrawWireFrame Toggle

    Now, in the WireFrame script, augment the condition in the if statement as follows:

    Делаю свой Майнкрафт на Unity

    2 дня назад сделал добавление своих источников освещения и всё работает весьма себе нормально. Главный косяк который остался, это межчанковое освещение, оно сейчас работает очень не стабильно.

    Сегодня занимаюсь ambient occlusion (что было затемнение в углах) и в целом прогресс мне нравится, хотя и понимаю что есть люди для которых это работы на пару часов.

    Если смогу добиться каких то интересных результатов, то создам полный пост о процессе создания каждого элемента.

    Люблю экзекуцию, что бы от сложности алгоритмов черви захлёбывались в крови. Дефолт в общем.

    Разработка своего клона майнкрафта это отличная учебная задачка.
    Я когда свой делал смог наконец более-менее разобраться с архитектурой мультиплеерных игр и многопоточностью.

    Про AO для кубов было бы интересно почитать. Я нормальную реализацию поленился делать, тупо пост-эффект навернул, но это плохой подход.

    Читать:
    Как найти наибольший общий делитель в c

Похожие статьи