Обзор + Скачать КАК СДЕЛАТЬ СВОЙ 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. Так как это вводный урок, алгоритмы и структура объектов, представленные в этой серии, не самые эффективные.
Приступаем к разработке
Скачайте последнюю версию Unity3D отсюда.
Скачайте текстуры, которые вам потребуются в процессе разработки проекта, описанного в этом руководстве.
- Текстуры куба:
- 16×16;
- 32×32;
- 64×64;
- 128×128;
- 256×256;
- 512×512;
Вы можете использовать любое из предложенных разрешений. Вы также можете скачать оригинал:
Для начала давайте познакомимся с Unity3D. Когда Вы запустите Unity3D в первый раз, всплывет окно Project Wizard. Вы можете импортировать один из встроенных пакетов Unity. Пакеты — это коллекции различных файлов (кода, моделей, аудио-файлов, текстур и т.д.), которые хранятся в виде иерархической структуры, инкапсулированной в файлы с расширением .unitypackage. Пакеты могут быть экспортированы из любого Unity-проекта. Таким образом можно очень просто переносить различные файлы между проектами, сохраняя их иерархию. Сейчас нам не нужно импортировать какие-либо пакеты.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Установка Wrap Mode для всех текстур проекта
Создаем куб
Было бы очень заманчиво использовать встроенный примитив Unity — куб — как основу для кубов Minecraft, и расположить соответствующие текстуры из текстурного атласа на стороны куба, используя UV-преобразования, но в этом руководстве мы будем придерживаться простых методик (с наименьшим количеством внешних ресурсов) и будем использовать отдельные меши для каждой стороны.
В верхнем левом меню кликните на GameObject → Create Other → Quad. Повторите это действие еще пять раз (нам нужно создать шесть сторон куба).

Создание граней куба
Теперь назовите каждую из шести сторон соответствующим именем:
Top, Bottom, Right, Left, Front, Back.
Объекты, расположенные на сцене, называются GameObject. Чтобы переименовать GameObject, кликните правой клавишей мыши на нем во вкладке Hierarchy и нажмите Rename.

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

Преобразование значений для каждой грани
Вуаля! Наш серый куб готов:

Обычный серый куб
Если куб не центрирован в окне Scene, дважды кликните на одной из его сторон во вкладке Hierarchy, чтобы выровнять камеру.
Во вкладке Project зайдите в папку Materials. Чтобы создать красивый пиксельный куб, мы должны переместить следующие материалы:
- TopMaterial на верхнюю сторону,
- BottomMaterial на нижнюю сторону,
- SideMaterial на левую, правую, заднюю и переднюю сторону во вкладке Hierarchy.

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

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

Создание пустого GameObject
Кликните правой кнопкой на объекте и переименуйте его:

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

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

Если вы обнаружили ошибки, как на картинке ниже, учтите, что это обычное явление, когда вы вручную меняете иерархию 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.)

Name the project.

3D should be highlighted.

Click the create the project.

Select the default 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

In the Hierarchy View , click the Create dropdown, select 3D Object and then Plane .
Inspector | Transform | Scale ( 16, 1, 16)

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)

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 game object.
In the Inspector , rename Cube to Block .

Select the Cube game object in the Hierarchy View first.

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

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 .

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.

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

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


Save the Scene and the Project
File | Save Scene
Select File and 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 .

File | Save Project
Select File and 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

Rename it to MineBlock .

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

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

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.

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.

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

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.

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.

Go back to Unity and run the game by clicking on the play button.
- 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.

In the Inspector View , uncheck the checkbox next to the game object’s 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 another Cube game object.
Rename it DroppedBlock .

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

Make it smaller.
Inspector | Transform | Rotate (15,0,5)

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 .

Select the source DroppedBlock Game Object and hide it.

Go to Mono and edit the MineBlock script by adding this line
before the Start function:

Go back to Unity and select the Block prefab.

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

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.


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.

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.

Go back to Unity and save the scene and project.


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

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 :

and download/import Standard Assets from there instead.
Assets | 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 the checkbox next to FirstPersonCharacter .

Now just the FirstPersonCharacter asset is selected.

Click the Import button.

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

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


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

Assets | Import Package | Utility


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 .

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

Drop it somewhere near the current camera.

Remove the old camera which is called 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 .

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.


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.

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

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

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 .

Rename the new script to MouseLock .

Select the 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 .

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

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

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.

To unlock the mouse cursor when the user presses the ESC key, put these lines
in the Update function.

Save the script.

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


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

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.

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.

From the File menu, select Build Settings. .
PC, Mac & Linux Standalone .

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

Select your operating system from the Target Platform menu.
Click the Build And Run button.

Name the application something like MakingMinecraft .


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

Check the Windowed check box.

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.)

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

When finished playing, press ESC to unlock the cursor and then close the application.
Back in Unity, close the Build Settings window.

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 .

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

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

Rename it to PickUp .

Select the DroppedBlock prefab again.

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

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

Save the scene and project.

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

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

Add the following OnTriggerEnter function
after the Update function like this:

Save the script.

Back in Unity, 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.

Breaking blocks and collecting dropped items is much more satisfying with sound effects!
Add Sound Assets.
Download the following two wav files:

Save them in the 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.

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

Sound Effect for Mining Blocks
In the MineBlock script in Mono, add this line
at the top of the MineBlock class:

Save the MineBlock script in Mono.

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 .

Drag the dig_grass1 asset into that field.

Go back to Mono and add this line
inside the OnMouseDown function before the Destroy statement.


Go back to Unity and save the scene and project.


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.

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:


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

Drag the pop asset into that field.

Go back to Mono and add this line
in the OnTriggerEnter function before the Destroy statement:


Go back to Unity and save the scene and project.


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.

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 .

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

About half volume feels right to me, but adjust to suit yourself.
Save the scene and project.



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 .

Select the Plane game object.

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

Double click the GenTerrain script to open it in Mono.

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


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

Drag the Block prefab into that field.

Back in Mono, add these lines
to the Start function in the GenTerrain class:


Back in Unity, select the FPSController game object

and adjust its Position

so that the player starts in the middle of the world and up high.
Delete the manually placed blocks.

Save the scene and project.



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.

It will be named New Material by default.

Rename it to BlockMaterial .

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


Close the Color selector.

Select the Block prefab in the Assets folder.

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

See the Element 0 field.

Drag the BlockMaterial asset into that field

Save the scene and project.


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

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 game object in the Hiearchy View . It will appear as a child of a Canvas object which get automatically created for this purpose.

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 in the Inspector for the Text game object.

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

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

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


Increase the font size a bit:

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

Go to Mono and select the PickUp script tab.

Add this using directive
at the top of the file:

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:

in the Start function:

Finally, put these lines
in the OnTriggerEnter function:


Go back to Unity and save the scene and project.


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

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.

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

Click Okay to create the new image.

In the zoom dropdown menu select 800%.

That way we can edit the image pixels easily.

Select the Pencil Tool from the Toolbox window.

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.

Maybe decorate them a bit.

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.

Select Color To Alpha. from the Colors menu.

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

Export the image to a PNG file.

Expand the Select File Type menu.

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

Select PNG image .

Now name the file crosshairs.png.bytes .

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.

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

Just click the Export button to accept the defaults.
Go to Unity and notice the new crosshairs.png asset in the Assets folder.

Go to the MouseLock script in Mono and add these lines
at the top of the MouseLock class:

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

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:

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.

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

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.

Save the scene and project.


The cursor should change to the crosshairs shape.

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.

Call 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)

Double-click the WireFrame script asset to open it in Mono and add the following lines
at the top of the class:

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.

Go back to Unity and create a new Material asset.

Name it WireMaterial .

Change it to black.

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

With the FirstPersonCharacter still selected, drag the Block prefab into the Target Block field of the 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:

to the Start function:

Add functions OnMouseEnter and OnMouseExit
at the bottom of the class after the OnMouseDown function:

to the OnMouseEnter function:

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:

Add these lines
to the OnPostRender function:

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:

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:

to the Start function:

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

Now, in the WireFrame script, augment the condition in the if statement as follows:
Делаю свой Майнкрафт на Unity
2 дня назад сделал добавление своих источников освещения и всё работает весьма себе нормально. Главный косяк который остался, это межчанковое освещение, оно сейчас работает очень не стабильно.
Сегодня занимаюсь ambient occlusion (что было затемнение в углах) и в целом прогресс мне нравится, хотя и понимаю что есть люди для которых это работы на пару часов.
Если смогу добиться каких то интересных результатов, то создам полный пост о процессе создания каждого элемента.
Люблю экзекуцию, что бы от сложности алгоритмов черви захлёбывались в крови. Дефолт в общем.
Разработка своего клона майнкрафта это отличная учебная задачка.
Я когда свой делал смог наконец более-менее разобраться с архитектурой мультиплеерных игр и многопоточностью.Про AO для кубов было бы интересно почитать. Я нормальную реализацию поленился делать, тупо пост-эффект навернул, но это плохой подход.