Unity - Conceptual ideas and tips for beginners igrodeva. Simple procedural model generation for a 2D game

  • Tutorial
Introduction to the problem

Hello dear readers!

Thoughts about creating a series of simple lessons “conceptual ideas for beginners igrodeva” came to me spontaneously, somewhere at 2:00 Moscow time during the creation of my current project. Well, no, it seems to me that it is spontaneous, but, probably, my subconscious mind reacted like that. It reacted because more and more young (which I myself am) and very young programmers decide to start creating games. It seems to me that the general trend of young programmers (and people interested in the field of programming) has smoothly moved from creating websites and fashion blogs to creating entertainment products. I am starting to notice this among my friends, who at one time said that, they say, games are not serious programming, but now they are already showing real interest in this environment.

I explain this to myself in the following, obvious way. Any informational trend acquires a massive tendency to study when two conditions are met: the presence of a simple and adequate tool for carrying out specific tasks in the selected information field and the ease of making a profit when selling your completed tasks. As an example, we can again cite the sphere of web technologies (once websites were created ultra-hardcore, and now, probably, even my mother can put a blog on WordPress or its analogues. Again why? Because WordPress opened the opportunity to create my own blogs to all moms around the world, and because websites have opened access to quick popularity, fame, money and rum).

But the era of entertainment came - I won’t mention how hard the first games were made, but decades passed, paid game engines began to appear, after a while they became almost free (Unity, Unreal Engine4), and not the engines from Vasya from a neighboring entrance in which you can only do “robbing of the cows”, and mastodon engines which are complex development environments that can realize your dream projects. However, there is a downside to these popular technologies. Namely, a large number of substandard products. Lazy to invent something of their own ... "I’d better make a fleppy bird!" Thought Vasya.

And I decided that I need to make a series of lessons consisting of simple ideas that people can use in their very first projects, people who, maybe, not so long ago began to study programming in general.

Random generation of 2D models (Unity)

When you make a game alone, it is not always possible to draw a large number of sprites for your characters, ships or buildings, objects in general.
Here procedural (random) generation comes to the rescue. What does this term mean in two (six) words? “The computer creates the model, not you.”

On the Internet, you can find millions of procedural generation algorithms in the field of game development (maybe one of them is even described by my mother in her own blog). Some of them will be simply complex (such as water surface generation using Nvidia Physics), others will be extremely complex, such as relief segmentation using fuzzy logic and fuzzy sets (Fuzzy Sets).

So what? I don’t think that the person who opens the unit for the second time will begin to think how to understand how to implement and in what place of the game to apply the found algorithm.

Easier to implement your own! Let it be simple, but understandable to you. And this is the most important step in all programming.
I offer you my version of the procedural generation of models (applicable to any 2D game). I warn you, the code is extremely simple! Two lines! But first, what you need to prepare before implementing the code:

1. Understand which model (or object) you want to create procedurally - it could be your knight, building, spaceship, etc.
2. Break into as many elementary parts as you want (for example, for a knight it can be a helmet, sword, shield, bib).
Note: the smaller the individual elements (for example, you break the sword into a hilt and blade), the obvious that your generated model will look more natural and unique.
3. Draw on each element as many different sprites as you see fit.
4.Build your model in the Unity editor the way it should look. I will use the model ship from my current project as an example.


Here are my details, sprites are scattered on the stage, from them I will assemble the model geometrically necessary for me.


And the code is coming!

using UnityEngine;
using System.Collections;
public class ChangeTextureF : MonoBehaviour {
      // в массиве Sprites будут находиться спрайты для каждой отдельной детали     
      public Sprite[] Sprites;                     
      void Start()
           // вызываем функцию сразу после создания объекта
      public void ChangeTextureFunc()                                                  
           // Подбрасываем псевдокубик в диапазоне от 0 до 
           // длины нашего массива, причем Random.Range 
           // не включает последний элемент      
           int ChooseForTexture = Random.Range (0, Sprites.Length);  
           // обращение к компоненту SpriteRenderer, и передача ему               
           // спрайта из массива наших заготовленных спрайтов по индексу,
	   // определенному рандомно строкой выше.        
	   GetComponent ().sprite = Sprites[ChooseForTexture];  

The ChangeTextureFunc () function contains only two lines of code, as promised.
Hang a script on each element of your object as shown in the screenshot. Drop the sprites of each element into an array directly in the editor, and enjoy the result.


Effective result:


PS Try to make the sprites for your model the same size so that there are no displacements in the model, however if you still want to make some very exquisite sprite that is fundamentally different in size from the main set, then just move it to the sprite editor'e Pivot point, which will determine the center of the sprite, as much as you need. Sometimes at Unity they forget about this feature.


Of course, I deceived you a little by saying that you will receive procedural generation of models, rather it can be called a quick combination of the model from the given sprites. But then I want to say in defense of this approach:
1) Well, there is no code, you draw three boats you divide each into three identical elements and at the output you get 27 model ships. Hurrah.
2) You will say that you are a cool brain and you can write an algorithm that will choose the ship’s contours and substitute its own color and you will have 1,000,000 combinations, but I’ll answer you that each of your models will be cracked because you don’t forget that game development including art. And 10,000 of your tasteless crazies will not be remembered by anyone.
3) For beginners, this will be an impressive result that can push them to develop this idea in breadth and depth.

By the way, there are examples that I came up with right while writing this article, how it can be interesting to use:
1) Attach a script to each element containing parameters that fit into the setting of your game, for example, for a spaceship it can be parameters: speed movement the ship, its damage, the number of hp or even abilities that will be acquired only from this type of part. Next, you throw at the main parent object, which contains all the details, a script that will collect parameters from each part, and, for example, summarize them and thus get the general characteristics of the boat.
2) The idea from point 1 can be used gameplay even deeper, for example, in some RPG game, where you can evaluate the opponent from afar not by the inscription “mob of level 80” but by his clothes, because before that you already saw similar elements the armor on the previous mob that was immune to fire and lightning. That is, without using any textual prompts, the player will experimentally find out the effect of certain things on the characteristics.

So what am I talking about? In creating a game, it’s not the main thing to chase after a super-complicated code that implements a million features; in creating a game, the main thing is to fish out a new and interesting idea with the minimum possible effort. Firstly, it will pump your resourcefulness and ingenuity, and secondly, you will save energy for the implementation of further new ideas. And then you can change the modern market of monotonous crafts ... Maybe you can gain fame, money, or just self-satisfaction. You started to make games for this?

Also popular now: