Unity тетрис как сделать

Unity тетрис как сделать

Этот урок возник в связи с тем, что мы делали обзор на другие источники и выяснили, что большинство из них напрямую завязаны на Unity. Мы же хотели бы сделать универсальное и максимально понятное, модульное решение, котороe не зависело от движка и могло быть использовано в любом языке программирования будь то Java, С++

Необходимые знания: двумерные массивы, циклы, создание объектов из кода в Unity

1. Создадим скрипт Tetris и повесим его на Main Camera.

2. Игровое поле зададим 2мерным массивом размером 16×8. Все действия будут происходить именно в массиве, а мы лишь будем визуализировать результат средствами Unity. Необходимо инициализировать его заполнив конкретными значениями, для того, чтобы было проще тестировать наш алгоритм.

3. Объявим двумерный массив из int’ов как глобальную переменную.

void Start() <
>
void Update() <
>
>
Это не размер оригинального поля, но вполне достаточно, чтобы тестировать основные моменты. В таком массиве
— пустое место,
1 — фигура, которая падает,
2 — блоки, которые уже упали.

4. Следующим шагом будет визуализация нашего массива. Для этого понадобится картинка блока тетриса размером 100×100 пикселей, чтобы в мире размер одного блока составлял 1×1 метр и нам не нужно было масштабировать наши блоки.

5. Из этого sprite создадим prefab. Можно пометить его static для частичной оптимизации.

6. В нашем тетрисе получим к нему доступ объявив публичную переменную
public GameObject pfbBlock;

7. Идея визуализации такова: мы изначально создадим все поле из квадратов, а потом будем включать и выключать их в зависимости от содержимого массива pole.

8. Нам очевидно потребуется получать доступ к этим блока и где-то их хранить. Будем их хранить в двумерном массиве из GameObject

9. Создадим ф-ю Fill, котороя и создаст все игровые блоки и поместит их в двумерный массив allBlocks.

10. Внутри Fill
allBlocks = new GameObjec t[ 16,8 ];
for ( int y= 0 ;y 16 ;y++) <
for ( int x= 0 ;x 8 ;x++) <
allBlocks[y,x] = GameObject .Instanciate( blockPfb ); //создаем и помещаем кубик в массив
allBlocks[y,x].transform.position = new Vector3 ( x, 15 — y, 0 ); //мы специально отнимаем от 15 y иначе наше поле нарисуется отраженным сверху вниз, потому что координаты в массиве идут вниз и вправо, а в Unity вверх и вправо.
>
>

11. Вызовем ф-ю Fill, после инициализации нашего поля.
Если мы сейчас запустим игру все поле должно быть в квадратах. Настройте камеру так, чтобы вы видели все игровое поле.

12. Создадим ф-ю Draw без параметров ничего не возвращающую

13. Вызываем ф-ю Draw в Update;

14. Внутри Draw будем анилизировать наш массив pole и в зависимости от того какое в нем число включать или выключать нужный кубик на экране. Для того чтобы пройтить по двумерному массиву нам понадобится for внутри for сначала по строкам, потом по x.
for ( int y = 0 ; y 16 ; y++) <
for ( int x = 0 ; x 8 ; x++) <
if ( pole[y,x] > 0 ) <
blocks[y,x].SetActive( true );
>
else <
blocks[y,x].SetActive( false );
>
>
>

15. После запуска игры вы должны увидеть ваше игровое поле на экране.

Источник

Unity тетрис как сделать

Framework: Unity 4.6
Language: C#
Source Code: Tetris.rar
Demo: Play Tetris

Introduction

This is actually one of the first projects I have ever built from scratch in Unity. I wanted to apply everything I have learned about programming in Unity and put them to the test. Before this, I looked up multiple Unity tutorials and worked with guided Unity projects. So, I see this like a homework assignment, where the purpose of it is to apply everything I learned on my own.

Читайте также:  Boom bap как сделать

This project is also interesting because, as I was working on this project, my friend and I wanted to challenge ourselves on making a Tetris game. We agreed on building a Tetris game before a certain deadline, and present our projects on that day. It wasn’t really a competitive challenge as much as it is a motivator for us to learn about Unity. However, the differences between my work and his is that, I decided to continue my Tetris project that I built on my own, while he wanted to use a certain tutorial to build his. It is an interesting tutorial, and you should check it out at http://noobtuts.com/unity/2d-tetris-game.

There were multiple tutorials I looked up, but there were two tutorials that helped me learn Unity the most:

  1. The Roll-A-Ball project tutorial from the official Unity site.
  2. Building Pong on Unity by the CEO of Brackeys.com

The Roll-A-Ball project helped me understand the Unity software editing tool and its navigation. It helped me understand how to adjust the prefabs, the project’s assets, writing the Unity scripts, and so much more. This is the project tutorial I highly recommend you to use when you want to use when you want to start building a Unity project right away, while learning how to navigate through the Unity tool. That way, you don’t have to get bored with learning how to navigate the tool, and not getting lost when you start building projects right away. Click here to go to that tutorial.

As for the tutorial building Pong on Unity, it mostly helped me on building a 2D game on Unity. Unity is mostly designed as a framework to build 3D games. It was recently made easier for developers to build 2D games with it, but there aren’t any good tutorials on the official Unity site for beginners who want to learn 2D game development. Luckily, I went to YouTube, and found a tutorial made by Brackeys on building 2D games with Unity by building a Pong clone. I suggest for anyone who wants to learn building 2D games for Unity for the first time to go to brackeys.com or click here to watch the Pong clone tutorial on Unity. You can even watch the first video tutorial below.

In this post, I will describe the implementation and structure of the Tetris project, as well as provide the source code and a link to play the game online. I recommend anyone who’s starting out with Unity and wants to learn from or contribute to the Tetris source code to go through the tutorials I mentioned above or any other tutorials that’s helpful first so that they have a better understanding of the project. I may post a tutorial in the future on building Tetris, but for the time being you can settle with the source code uploaded online.

The Tetris Block

As we all know , the Tetris pieces are made up of four blocks, with the formation of the blocks creating different shapes for differenty pieces. So, the most important prefab in the entire game is the Tetris block.

You can create the Tetris block sprite with pretty much any paint program that is capable of creating PNG logos, since the design is nothing more than just a square with borders surrounding it. I used Paint.NET to create a PNG white square with black borders.

After that, I added the sprite PNG to Unity, and created from it the block game object. This is done by importing the PNG sprite to the Project panel, then dragging the PNG srpite to the Hierarchy panel, which converts the PNG to a game object. I then dragged and dropped the newly created game object to the Project panel to create a prefab that we can use later to create the Tetris pieces.

Читайте также:  Ирис как сделать ник

With the Tetris block game object and prefab created, I used them to create the seven Tetris pieces. I did that by creating an empty game object that contains four tetris block, with different formation for each block. The coordinates of the blocks inside the empty object are used to create the different formation of the Tetris object. I also changed the color for each block of each Tetris piece to distinguish one Tetris piece from the others. You can do that by changing the color of the sprite in the Sprite Renderer component in the Inspector panel.

With the Tetris pieces created, I dragged and dropped them to the Project panel to turn them into prefabs.

Other Game Objects

The other game objects were either downloaded, or quickly created on PAINT.NET.

  • The grey background and black borders of the Tetris board (Next to the Scores and “Next Piece” section) were created on PAINT.NET. I initially wanted to create invisible wall using box colliders provided by Unity. However, because I changed the way the game is created, I got rid of the invisible walls. but kept the black borders for decorations.
  • The background with the stars is an image I extracted from Google search. I wanted a nice background image to fill the screen other than a single color background usually provided by Unity.
  • As for the text on the right side of the screen and the “game over” screen, they were text sprites provided by Unity, but with fonts downloaded from the Unity Asset store called “Computer Font Pack”, which has fonts resembling the ones that existed in 1980s computers.
  • The Tetris background music is the Gameboy Tetris theme loop that I found on Youtube. I had no music to provide, so I needed a way to fill the void of silence.
  • The logo in the menu screen was the EA Tetris logo I also managed to find from Google search.

The MainGame Object

This is a game object I created to put all of the other game objects under. I need a way to create a script that controls the game as whole rather than each game object having their own script. The nature of the game “Tetris” can’t have the game objects being controlled individually. Therefore, I created the MainGame object containing all other objects in order to unify the game logic.

The GameManager Script

This is the script that contains all of the logic of the game. It manages the rotation, moving right and left, showing what comes up next, calculating the score, and so on.

The coordinates and collision detection in the game that I created are based on the 2D grid array I also created called “blockSpace”. This array is made up of integers, in which each array index represents the coordinates of the playing field, and each integer is used to represent the state of the coordinates.

Let me briefly explain about Update() and FixedUpdate() in the script. I will not explain exactly how they are used in Unity in general since you have to read up on how to use Unity in order to understand that, but I will explain how I use them in my script.

  • Since Update() contains events that occurs once per frame, I use it to handle almost all inputs of the game, and some collision detection, such as blocks on the right or left
  • Since FixedUpdate() contains events that occurs once per fixed frame (until certain frame occurs at a certain time), I use it to handle almost all collision detection of the game, as well as some input, such as rotating the Tetris piece at the very last second before lnading at the bottom.
Читайте также:  Архикад как сделать землю

Conclusion

Tetris is an interesting project to start with when learning Unity. It doesn’t go deep into Unity and utilize everything Unity has to offer, but I do consider it sort of like a bootstrap on learning building 2D games for Unity.

Tetris is a game where, unlike most Unity projects I’ve dealt with in tutorials, it cannot be controlled by having each game object with its own script. Rather, it is managed by having one script contained in the main game object. It is basically a game that utilizes the concept of a master command center in order to manage the game.

Try it out

If you would like to try the game online, click here. You can also download the source and contribute to the project here. I will also upload the source code to Github as soon as I establish my account in it.

If you can’t play the game on Chrome, try using a different broswer like Internet Explorer or Mazolla Firefox.

If you have any questions, please leave a comment or contact me by email.

Источник

2D Tetris Clone Game Tutorial – Unity3D (C#)

2D Tetris Game Tutorial – Unity3D (C#)

Do you remember the most famous single player game of early 90s? Yes, it’s Tetris. Developed by a Russian engineer, Aleksey Pajitnov, in 1985. Tetris is the 6th most played game ever. We will make our Tetris game in this tutorial.

The goal is to collect moving downward blocks at bottom with no gap in 2D. Game ends when there is no available area for new block.

Before start coding, please create or download your block texture (square) and wall texture. You can find the on google or download images below.

Open a 2D project in Unity3D and import these images. Cube images size is 32×32, so please edit Pixel Per Unit as 32 which means 32 pixels will be placed in 1 game unit. We need 7 different game object for blocks. Every block is created by 4 independent cubes because we will delete cubes separately when a row is full, not whole the object. By the way, we need J, T, S, Z, L, I, O-shaped blocks as you know.

To create blocks, create an empty game object named Block_J and create 4 cubes from cube image. Assume that there is a 4×4 square and Block_J is at the center (0, 0). Place cube objects in this 4×4 area. Be careful, you must placed cubes on squares perfectly to get best fit on game. You can see an example below.

Place all cubes in block objects as seen as picture below. Create prefabs (create a Prefabs folder under Assets in Project window and drag blocks) and delete blocks in scene.

We will check available area and restricted grid for cube movement, so you don’t need to add 2D collider to boxes and walls.

Create a C# script name SpawnBox and write code below.

Источник

Поделиться с друзьями
Ответ и точка