How to create a game using the unity3d engine. Working in Unity3d: the basics of creating games. Setting up your environment in Unity

In the first chapter you will find basic information on downloading and installing Unity and preparing the first scene of our game.

Setting up your environment in Unity

Let's start with the simplest thing: downloading and Unity settings.

Download latest version from the official website or torrent and run the installation file.

To edit code in Unity (4.0.1 and higher), use the MonoDevelop editor. If you're on Windows, you can (and I recommend) use the Visual Studio 2013 Desktop (C#) alternative editor for Windows, and then change the default editor to Visual Studio in Unity preferences.

Good to know: It is not possible to use the Visual Studio 2013 Express debugger with Unity. You must have Pro version Visual Studio and buy UnityVS plugin. With the Express version, you'll have a better code editor, but the lack of a debugger will negate any of its benefits.

Mac OS X

A note about the Resources folder: If you've worked with Unity before, you know that the Resources folder is a useful and unique folder. It allows you to load an object or file into the script (using the static Resources class). We will need it at the very end (in the chapter on the menu). Simply put, we won’t add it yet.

Our first game scene

Panel Hierarchy(Hierarchy) contains all the objects that are available in the scene. This is what you manipulate when you start the game using the "Play" button.

Every scene object is a game object for Unity. You can create an object in the main scene, or in another game object. You can also move an object at any time to change its parent.


As you can see here, we have 3 children here for the Level object.

IN Unity you can create an empty object and use it as a "folder" for other game objects. This will simplify the structure of your scene.

Make sure they all have coordinates (0, 0, 0) so you can find them easily! Empty objects do not use their coordinates in any way, but they do affect the relative coordinates of their children. We won't talk about this topic in this tutorial, let's just reset the coordinates of the current empty objects to zero.

Filling the scene

By default, a new scene is created with a Main Camera object. Drag her onto the stage.

First, create these empty objects:

Scripts We will add our scripts here. We use this object to attach scripts that are not associated with the object - for example, a game manager script. Render This is where our camera and light sources will be. Level

In Level create 3 empty objects:

  • 0 - Background
  • 1 - Middleground
  • 2 - Foreground

Save the scene in the Scenes folder. Call it whatever you like, for example Stage1. Here's what we got:

Tip: By default, the game object is bound to the parent's position. This leads to an interesting side effect when using a camera object: if the camera is a child object, it will automatically track the parent's position. If it is the root object of the scene or is inside an empty game object, it always shows the same view. However, if you place the camera on a moving game object, it will follow its movements throughout the scene. In this case, we need a fixed camera, so we put it in an empty Render object. But remember this property of the camera object, it may come in handy. We'll go into more detail on this topic in the chapter "Paralax Scrolling".

We've just created the basic structure of our game. In the next step we'll start doing some fun things: adding a background to the scene and a few other things!

Adding a background to the scene

Our first background will be static. Let's use the following image:


Import the image into the Textures folder. Just copy the file into it, or drag it from Explorer. Don't worry about import settings for now.

Create a new Sprite game object in Unity on the stage.

What is a sprite?

Essentially, a sprite is a 2D image used in a video game. In this case, it's a Unity object for creating 2D games.

Adding a sprite texture

Unity can automatically set a background for your sprite. If nothing happened, or if you want to change the texture, go to the inspector tab and select background: (background)


You must click on the small round icon to the right of the input field so that Select Sprite appears in the Inspector

My sprite doesn't appear in the dialog! Make sure you are in the tab Assets Select Sprite dialog box. If you see the dialog box empty, don't be alarmed. The thing is that for some Unity installations, even with a fresh new 2D project, the images are imported as a "Texture" rather than a "Sprite". To fix this, you need to select the image in the "Project" panel, and in the "Inspector", change the "Texture Type" property of the "Sprite" property:

So, we have created a simple sprite that displays clouds in the sky. Let's make some changes to the scene. In the panel Hierarchy(Hierarchy) select New Sprite. Rename it Background1 or something easy to remember. Rename it Background1 or something easy to remember. Then move the object to Right place: Level -> 0 - Background . Change the coordinates to (0, 0, 0) .


Create a copy of the background and place it at (20, 0, 0) . This should fit perfectly into the first part.

Tip: You can create a copy of an object using cmd + D on OS X or ctrl + D on Windows.

Sprite Layers

The next statement is obvious, but has some inconveniences: we are displaying a 2D world. This means that all images are at the same depth, i.e. 0. And you graphics engine doesn't know what to display first. Sprite layers allow us to define what is in front and what is behind.

In Unity we can change the "Z" of our elements, allowing us to work with layers. This is what we did in this tutorial before upgrading to Unity 5, but we liked the idea of ​​using layers with sprites. Your component has Sprite Renderer there is a field with a name Sorting Layer with default value. If you click on it you will see:

Let's add some layers to suit our needs (use the + button):

Add a background layer to your background sprite:

Settings Order in Layer is a way to limit sublayers. Sprites with lower numbers appear in front of sprites with higher numbers.

Layer Default cannot be deleted because it is a layer used by 3D elements. You can have 3D objects in a 2D game, in particular particles are treated as 3D objects by Unity so they will be rendered on this layer.

Adding background elements

Also known as props. These elements do not affect the gameplay in any way, but they allow you to improve the game's graphics. Here are some simple sprites for flying platforms:


As you can see, we have placed two platforms in one file. This good way learn how to crop sprites using new tools Unity.

Getting two sprites from one image

Follow these steps:

  1. Import images into the "Textures" folder
  2. Select the Platform sprite and go to the Inspector panel
  3. Change "Sprite Mode" to "Multiple"
  4. Click on the Sprite Editor button

In a new window (Sprite Editor) you can draw rectangles around each platform to cut the texture into smaller pieces:


The Slice button in the top left corner will allow you to quickly and automatically do this tedious job:

Unity will find objects inside the image and will cut them automatically. You can set a default value for the pivot point or a minimum size for each fragment. For a simple image without artifacts, this is unusually effective. However, if you use this tool, be careful and check the result to make sure you get what you want.

In this tutorial we will do this operation manually. Name the platforms platform1 and platform2. Now, below the image file, you should see two sprites separately:


Let's add them to the scene. To do this, we will perform the same actions as for the background: create a new sprite and select platform1. Then we will repeat these steps for platform2. Place them in object 1 - Middleground. Make sure their Z position is zero.


Prefabs


This way you will create a Prefab that matches the original game object exactly. You'll see that the game object you converted to Prefab is a new row of buttons right below its name:


A note about "Prefab" buttons: When you subsequently modify a game object, you can use the "Apply" button to apply those changes to the Prefab , or the "Revert" button to undo all changes to the game object in the Prefab property. The "Select" button will move the selected properties to the Prefab asset in the project window (they will be highlighted).

Creating prefabs with platform objects will make them easier to reuse. Just drag and drop Prefab to the stage to add a copy. Try adding another platform in the same way.

Now you can add more platforms, changing their coordinates, sizes and planes (you can place them in the background or foreground, just set the platform's Z coordinate to 0).

At this stage it all looks crude, but in the next two chapters we'll add parallax scrolling and the scene will come to life before our eyes.

Layers

Before we move on, we'll modify our layers to avoid any issues with their display order. To do this, simply change the position of game objects along the Z axis in the tab Hierarchy(Hierarchy) as follows:

When switching from 2D to 3D mode, you will clearly see the layers in the Scene window:


When you click on the Main Camera game object, you will see that the Projection checkbox is set to Orthographic. This setting allows the camera to render a 2D game without taking into account the 3D properties of objects. Keep in mind that even if you are working with 2D objects, Unity still uses its 3D engine to render the scene. The picture above clearly demonstrates this.

In the next lesson:

You've just learned how to create a simple static background and how to display it properly. Then we taught you how to make simple sprites. In the next chapter we will learn how to add a player and his enemies.

How to create a game in Unity

Casual games in the match 3 (three in a row) genre are among the most popular on the market. Many people play Candy Crush, Bejeweled and others. These games have a simple goal: move tiles until three identical pieces are adjacent. When this happens, the matching elements disappear and others appear in their place. At the same time, the player gains points.

This guide will cover the following:

  • Create a board filled with tiles
  • Selecting and deselecting tiles
  • Identifying neighboring elements using raycasts
  • Replacing elements
  • Finding matching three or more elements using raycasts
  • Filling Empty Elements
  • Keeping score and counting movements

Note. It assumes that you already know how to use the Unity editor, how to edit code, and that you have a basic knowledge of C#.

In the future, you can add temporary modes, different levels with boards of different sizes, bonus points for combinations, or animation effects.

Share this article:

Related Articles

Development mobile applications is one of the most lucrative occupations in the computer industry. Creating a game on Android costs several hundred or thousand dollars, and the profit can reach a million dollars. In this regard, many people are interested in developing applications for their phones. In this article you will learn about how to create a game on Android from scratch using a computer, which engine and designer is better to choose.

None successful game is not complete without beautiful graphics, so creating a design is one of the most important stages of development. Design on the Android OS is implemented using a “design document” or design document. You need to start creating a toy with its detailed elaboration. The file contains:

  1. Object models;
  2. Functional specifications;
  3. Game content;
  4. Interface.

Let's consider each of the points in more detail.

Object Models

This is information about the functionality of each item. Object models are responsible for the ability to buy and sell items, as well as for improving the game characteristics of characters.

Functional Specifications

The gameplay and the main capabilities of each character are described here. Also here is a description of the features game items– weapons, first aid kits, armor and others. Essentially, functional specifications are the rules by which game process. The better this section is worked out, the easier it will be to create a high-quality Android game.

Game content

This is the text content of the game. It describes the dialogues of the characters and what weapons can be used to cause damage, how much health a hit will take, and what characteristics will increase when using various equipment. Also contained here detailed description each item.

Interface

The interface is how the user will interact with the game. It includes buttons with which you can control the character, and menu sections: for example, play, score, settings, top players, help. If you do not have experience in creating applications on Android, before creating your own, download from the Play Market and analyze popular games and transfer the best solutions to your project.

Game engine

The basis of any game is the engine. This software, allowing you to develop and run it. It contains a whole range of programs, including a rendering engine, a physics engine, sound, animation and much more. To make the process of writing programs easier, third-party developers create their own game engines specifically for Android applications.

Each offers different features: some are designed for 3D, others for 2D, and can support multiplatform. There are a huge number of such engines, but if you are a beginner, it is better to choose one of the most popular ones, since all the necessary functions will be present there.

UDK

Torque 2d/3d

What is a game designer?

The designer is a program that combines a game engine and an integrated development environment. The designer makes the development process accessible to people who do not have programming skills. Some of the designers allow you to create games of certain genres, others have maximum functionality, but cost much more money. For a beginning mobile application creator, choosing a designer is one of the most crucial moments, because the fate of the future application will depend on its capabilities.

The designer allows you to create games of various genres for Windows, Android and iOS. Offers big choice ready-made locations, objects, characters and sound designs, so creating your first Android game will not take much time. Users familiar with the JS and C++ programming languages ​​can use the embedded GML. The only drawback is that the program is not translated into Russian.

Conclusion

Creating a game on Android is not an easy task, but it is very profitable. If you decide to develop a game and make money from it, first work out the idea. Next, write a “design document” and decide on game engine who can maximize its potential. After this, you can proceed directly to creating the application in the designer.

Video

To learn more about the process of creating Android games, check out the series of videos dedicated to this activity.

Prologue.
Hi all. When I learned about Unity3D, I was very happy. This was the second thing in game development that hooked me with its simplicity and intuitiveness (the first was Game Maker). Since I don’t like video lessons (I don’t know why), I was very stressed in searching for lessons, due to the small number of text lessons. Therefore, I decided to write this series of articles for those who love text lessons like me. Since this series is aimed at beginners, the capabilities of Unity3D will be explored along the way.
Lesson 0 or small plan.

“The future must be built in the present. This is called a plan.
Without it, nothing in the world can be good."
Georg Christoph Lichtenberg


1. Create a menu with a flying camera ala Far Cry.
2. Character. Movement and control. Camera. We change the position and view of the camera.
3. Stats. Part one. Experience, money.
4. Quests.
5. Ai. Artificial intelligence. Part one. Purchasing a character.
6. Stats. Part two. Life, manna. Draw HP and MP bars.
7. Ai. Artificial intelligence. Part two. Mobs.
8. Inventory. Shop.
The plan may be supplemented and changed.
Lesson 1. Menu with a flying camera ala Far Cry.
In this tutorial we will learn the basics of creating scenes in Unity3D. Let's learn some standard features and some additional ones.
Used:
1. Terrain Toolkit http://yadi.sk/d/NECQRcVaCEKuT
2. Nature Pack http://yadi.sk/d/m8Qu8ts2CEKyB
3. Real Nature Pack 2 Autumn v2 http://yadi.sk/d/A4IN7tuMCELA3
4. Tropical Nature Pack http://yadi.sk/d/lTMMWzC4CELCf

Plan:
1. Creating a project. Import the required libraries.
2. Landscape generation. Editing.
3. Lighting. Camera.
4. Camera animation (flight).
5. Menu creation.
Creating a project. Import the required libraries.
Let's launch Unity. In the “Project wizard” go to the “Create New Project” tab. In "Import the following packages" select the following packs: Skyboxes, Terrain Assets, Water (depending on the version of unity3d, I chose pro)

Go to “Assets>>Import package>>Custom package” and go to the folder where you have the downloaded packages. Select and click open.

Attention!!! The packs are heavy, so Unity may give you some thought, don’t be alarmed!!
Landscape generation.
Click “Terrain>>Create Terrain”

The “Terrain” object has appeared
Click “Terrain>>Set Resolution” And set the dimensions of our landscape as in the screenshot. For the scene, a menu for a large landscape is not needed and in order not to load the processor, these sizes are enough.

Click “Set Resolution”
Click “Component>>Terrain>>Train Toolkit”


In the “Terrain Toolkit” component that appeared, I set everything like this


I advise you to play with the settings; very often such interesting landscape options appear.
So our landscape is ready.
Let's give it a texture.
In the inspector, click on the brush and then Edit Textures.

And click Add Texture. In the window that appears, click “Select” on Texture

In the window that appears, select the texture (double click the mouse), I chose “Grass (Hill)”


Click Add and our landscape is repainted.


Click “Raise/Lower terrain”


Select the brush, Brush Size and Opacity. And by pressing LBM (Left mouse button) we raise the vertex, or by pressing Shift+LBM we lower it.
By pressing “Smooth Height” (3rd button) we remove sharp corners.
Next I painted something like a sandy beach adding a “Good Dirt” texture.
Here's what I got.

Select “Place trees” and click “Edit trees”. In the window that appears, click the circle.
And similar to choosing a texture, choose wood.
And by varying the brush settings we plant different trees.
Similarly, on the penultimate button we plant flowers, grass, stones, etc.
With one BUT, in order not to load the processor, we select “Add Grass Texture” for the grass, but “Add Details Mesh” for the rest.
And in the last tab you can play around with the tree settings, rendering, and wind settings. I left everything as standard.
Let's create water. In the “Project” window, go to the “OnQ Nature Pack 2 v2>>Resources Demo>>Standard Assets>>Water(pro only)” pack and select “Daylight water”.

We drag it onto the stage and use the transformation buttons to position and stretch it as we need.

Here's what I got.


This is the end of the landscape.
Now let’s add “Skybox”. To do this, go to “Edit>>Render Settings”.

And in the inspector, select the “Skybox” material by clicking on the circle.


I chose "Sunny2 skybox".
Lighting and camera.
In “GameObject>>Create Other” select “Point light”.

In the inspector we set the settings. “Position” x=100 y=100 z=100 this will center our light source above the “Terrain” at a height of 100. “Range” = 150, this is the radius of the light around the source. And "Itensity" = 3.3.


The result is a fairly soft light that reaches everywhere.


We already have a standard “Main Camera” camera created. Click on it in the Hierarchy window. And place it at position X=10, Z=10. A Y is set relative to the height of your landscape, I got 45. To reduce the area captured by the camera, change the “Field of View” setting (I have 43). Focusing on the “Camera Preview” window, we rotate the camera as we need it. I got Rotation X=5, Y=45, Z=0.
Camera animation (flight)
Go to “Window>>Animation” or press Ctrl+6. Click on the arrows in the empty field and select “Create New Clip”

Let's call it “CameraFly” for example. Click on the wand opposite “Position.x” and click “Add Curves”. Let's set the frame position to 300 and set the necessary coordinates for the next camera position.
I got the following values:

200?"200px":""+(this.scrollHeight+5)+"px");">
Variable/frame number 300 | 600 | 900 | 1200 | 1500| 1800
Position.x 90 | 10 | 190 | 120 | 190 | 10
Position.y 45 | 45 | 45 | 45 | 45 | 45
Position.z 90 | 190 | 190 | 100 | 10 | 10
Rotation.x 5 | 45 | 15 | 15 | 15 | 15
Rotation.y 45 | 94 | 240 | 140 | 270 | 405
Rotation.z 0 | 0 | 0 | 0 | 0 | 0


Let's click on the Play button and see what happens. And now our camera is already flying. However, after flying around the circle, she stops. Let's fix this.
Let’s create a new C# script (RMB in the “Project” window, then “Create>>C# Script”) and call it FlyCamera. In it we write just one line in the Update method:

200?"200px":""+(this.scrollHeight+5)+"px");">
transform.animation.CrossFade("FlyCamera");


This forces us to perform an animation called “FlyCamera” cyclically. We place the script on the Main Camera.
We check and everything works).
We create a menu.
Let's create a script called "Menu".
Let's set the variables:

200?"200px":""+(this.scrollHeight+5)+"px");">
public bool showMenu = true; //Whether to display the menu


In the “Start” method we write:

200?"200px":""+(this.scrollHeight+5)+"px");">
showMenu = true;
window = 1;


In the “Update” method we write:

200?"200px":""+(this.scrollHeight+5)+"px");">
{
}
if(curTime >
{
window = 0;
}
{
window = 1;
}


We create the “OnGUI” method and write into it:

200?"200px":""+(this.scrollHeight+5)+"px");">
{


{
}
{
}
{
}
{
}
}

//Then everything is the same
if(window == 2)
{

{
}
{
}
{
}
{
}
{
window = 1;
}
}

If(window == 3)
{

{
window = 1;
}
}

If(window == 4)
{

{
}
{
window = 1;
}
}


{
useGUILayout=false;
}
}


We move the script to Main Camera.

Let's save the scene called menu.unity

Full code menu script

200?"200px":""+(this.scrollHeight+5)+"px");">using UnityEngine;
using System.Collections;

Public class Menu: MonoBehaviour (
public bool showMenu; //Whether to display the menu
public int window; //Displayed window
public float lifeTime = 5.0f; //Maximum menu display time
private float curTime; //Current menu display time

Void Start() (
showMenu = true;
window = 1;
}

Void Update() (
if(showMenu == true) //Check if the menu is enabled
{
curTime += Time.deltaTime; //If enabled, Increment the curTime variable according to the elapsed time
}
if(curTime > lifeTime) //If time has reached the maximum point
{
showMenu = false; //Disable the menu
window = 0;
curTime = 0; //Reset the timer
}
if(showMenu == false&Input.anyKeyDown) //If the menu is turned off and any key is pressed
{
showMenu = true; //Enable menu
window = 1;
}
}

Void OnGUI() (
if(window == 1) //If window is 1
{
GUI.Box(new Rect(Screen.width/2-100,Screen.height/2-80,200,220), "Menu"); //Create a window with a menu

If(GUI.Button (new Rect (Screen.width/2-90,Screen.height/2-40,180,30), " A new game"))
{
Application.LoadLevel(1); //Load level 1
}
if(GUI.Button (new Rect (Screen.width/2-90,Screen.height/2-0,180,30), "Settings"))
{
window = 2; //open the settings window
}
if(GUI.Button (new Rect (Screen.width/2-90,Screen.height/2+40,180,30), "About the game"))
{
window = 3; //Display information about the game's Authors
}
if(GUI.Button (new Rect (Screen.width/2-90,Screen.height/2+80,180,30), "Exit"))
{
window = 4; //Call the exit window
}
}

//Then everything is the same
if(window == 2)
{
GUI.Box (new Rect (Screen.width/2-100,Screen.height/2-80,200,250), "Settings");
if(GUI.Button (new Rect (Screen.width/2-90,Screen.height/2-40,180,30), "Game"))
{
}
if(GUI.Button (new Rect (Screen.width/2-90,Screen.height/2-0,180,30), "Audio"))
{
}
if(GUI.Button (new Rect (Screen.width/2-90,Screen.height/2+40,180,30), "Video"))
{
}
if(GUI.Button (new Rect (Screen.width/2-90,Screen.height/2+80,180,30), "Control"))
{
}
if(GUI.Button (new Rect (Screen.width/2-90,Screen.height/2+120,180,30), "Back"))
{
window = 1;
}
}

If(window == 3)
{
GUI.Box (new Rect (Screen.width/2-100,Screen.height/2-80,200,220), "About the game");
GUI.Label(new Rect(Screen.width/2-90,Screen.height/2-0, 180, 40), "Info about the developer");
if(GUI.Button (new Rect (Screen.width/2-90,Screen.height/2+100,180,30), "back"))
{
window = 1;
}
}

If(window == 4)
{
GUI.Box(new Rect(Screen.width/2-100,Screen.height/2-60,200,120), "Exit?");
if(GUI.Button (new Rect (Screen.width/2-90,Screen.height/2-20,180,30), "Yes"))
{
Application.Quit(); //Exit the game
}
if(GUI.Button (new Rect (Screen.width/2-90,Screen.height/2+20,180,30), "No"))
{
window = 1;
}
}

If(window == 0) //If this is a window then turn off the menu
{
useGUILayout=false;
}
}
}


Compiled scene http://yadi.sk/d/f5pFI0_pCG7YC

P.S. Please do not judge strictly, this is my first article.
P.P.S. For trolls: yes, I’m a redneck coder, go through the forest!



Game engine Unity 3D. Course of Study

Table of contents 1. Preparing for work: Where to download, how to install, what you need to know, what to follow.
2. Program interface: Main Menu, Project Overview, Hierarchy, Scene, Game View, Inspector.
3. The simplest game: Create a project, Create a game scene, Create a script.
4. The simplest game (2): Ability to shoot, How to add enemies, Enemy controller.
5. The simplest game (3): Particle system, Adding sounds, Creating text on the screen, Publishing.
6. 3D platformer. (in process)

3. The simplest game

To begin with, we would like to create the most simple game, in order to quickly go through all stages of development, not be distracted by small nuances, and in practice see that it is still possible - to manually create your game. For this purpose, we will choose as a reference one of the first games in history - SpaceWar. This is a 2D shooting game where a spaceship flies through space and shoots at another ship. Minimum graphics, only pure mechanics. (But graphically, we can certainly afford more interesting images than monochrome pixels).

Agree, a good way to learn is not to study many separate, unrelated functions, but to recreate them yourself meaningful games the entire history of development computer games, from primitive to the most modern.

3.1. Create a project

1. After starting Unity, in the top main menu select “ File -- New Project"(file – create project).

In the window that appears, select a location on your hard drive where to save the project. We recommend writing the folder path as short as possible, for example: C:/Project_1.

Below in the window there is a list from which you can select standard additional packages for the game, but for the first project we don’t need anything yet. (Any extra library added to the project will increase the size of the final game.)

At the bottom of the window, select the two-dimensional game “Setup defaults for: 2D».

After that, press the button “ Create" (create).




2. A Unity window opens in front of us, consisting of several zones. The location of the zones can be immediately customized in the “View” section of the main menu, so we will be guided not by the sides of the screen, but by the names of Unity’s work zones.


Let’s immediately make a reservation that we will comply with all program development standards: a clear hierarchy, meaningful variable names, comments in the program code. (In general, these are not mandatory actions; they slightly increase development time, but significantly increase the usability of the program for other people. If you are going to create games in a team with like-minded people, then you just need to adhere to the standards. But even if you are developing alone , the project may be so large that at some point you will forget part of the code, and you yourself will not be able to quickly figure it out. To prevent this from happening, we leave comments everywhere. Program design standards will help you quickly understand your own long-forgotten code).


3. Let’s create a clear project hierarchy by creating folders for each type of file:

1). In the window " Project"In its upper left corner, press the button " Create».

2). In the list that appears, select “ Folder"(folder). A new folder will appear in the root Assets folder.

3). We create four folders and name them like this:

Prefabs(prefabs are arrays of objects),

Scripts(scripts – program code),

Sounds(sounds – for sound accompaniment of game actions),

Sprites(sprites are images for game objects).

(Created folders can be renamed and moved at any time by dragging and dropping items in the Project window.)

4). This is what it should look like final result our operation:



3.2. Creating a game scene

Let's create the main game object, which will be directly controlled by the player. In our case, this is a spaceship.


Create a sprite:

1. Open the Paint program. In the image properties, change the size to “100 x 75”. We draw a ship from the simplest shapes, paint it over, and leave the color white around the ship. Save the file under the name "".

2. Open the created file in the Gimp program. On the left, select the “magic wand” tool, select the white area around the ship in the image. In the main menu, on the “Image” tab, select the last line “Color to alpha-cannel”. After this, there will be a transparent color around the ship. If there are still white areas in the image, repeat the steps until we have desaturated everything unnecessary. Save the file. We remember the folder where the created file is located.

(It doesn’t matter what the ship will look like, as long as its silhouettes are clearly visible and there is transparency around it. If you’re really bad at drawing, you can download an image of the ship directly from this page).


Images needed to create a game
Ship
Space
Alien
Shot

Create a game object:

1. In another window, find the image file on the computer that we just created, drag it into the Unity window in the “ Project"to the folder" Sprites" The file will be downloaded to the folder. After this, select the downloaded file in the “ Inspector" in the line " Texture Type" select the value " Sprite (2D and UI)" Click the button below Apply"(apply).


(Another way to add files: in the “Project” zone, select the “Sprites” folder, click on it right click mouse, in the list that appears, select “Import New Asset”, in the window that appears, look for the location folder and the image file itself).

2. Select the downloaded file in the “ Project", drag it to the " Scene(dark gray part of the Unity working window, where there is a video camera image).

On the right in the “Inspector” zone we look at the “Transform” characteristics - these are the coordinates of our object in the game space. After dragging, the object was not positioned correctly (the X and Y coordinates are fractional numbers, not integers). Right-click on the menu " Transform", in the list that appears, select " Reset Position" After this, the image will be positioned exactly in the center of the world (X=0, Y=0).


Create the background:

1. Draw an image of starry space - a dark background and several stars. Image size - 100 x 100, format - .png. You can use a ready-made image file from our website.

2. Add the created file to the Unity window in the “Sprites” folder.

3. Drag the file into the game scene window. As we can see, the new image has stood on top of the old one, and the ship is now almost invisible. Unity, and indeed all editors, are designed in such a way that new elements are placed on top of the old ones, but we need the background to be in the background. To correct the order of images, select the game object with the background in the “Inspector” window in the properties “ Transform" insert the value " Z=1" The ship image should have the property “Z = 0”. Z is the depth of an object in 2D games. The higher the Z value, the farther the object is from the game camera.


4. Another way: select the background object on the stage, look at the properties in the “Inspector” window Sprite Renderer", in the line " Sorting Layer"Press the button and select " Add Sorting Layer" After this, a new line will appear with the name of the layer “Layer 1”, rename it to “ Background" In the same way, create two more layers: “ Foreground" And " GUI».

5. Select the ship object, in the “Inspector” window, in the “Sorting Layer” line, set it to the “Foreground” layer. Select a background object and set it to “Background”. The ship will now appear on top of the background.



Our background image is currently 100 x 100 pixels. This will not be enough for the background. Of course, you can create many copies of this image and cover the entire game screen with them, but this is a very time-consuming and ineffective method. We'll go the other way: turn the sprite into a texture.


6. Select the background object from the list “ Hierarchy" and delete it ("delete" key) to remove the background from the game scene. In the zone Project"select the background image in the window" Inspector"change its type" Texture Type" on " Texture" In the “Wrap Mode” line set the value to “Repeat”. Press the button " Apply" (Site site)



7. We have a texture, now let's create a suitable game object for it. In the top main menu, select the line “ GameObject | Create Other | Cube" Change the name of the appeared object to “Background”. In the “Transform” properties, change the location “Position: 0, 0, 1 " and size "Scale: 100, 100, 1 ».

By creating such a large cube in the background, we obscured the entire part game world displayed on the monitor screen.

8. In the properties of the cube, delete the section “ Box Collider" (collision handler). To do this, right-click on the section, in the menu that appears, select the line “ Remove Component».



9. Our background image cannot be directly placed into a 3D object. First, the image needs to be converted into material. In the zone Project"click on top" Create | Material" We call the material that appears “BackgroundMaterial”. In properties " Shader"click on the drop-down menu, select " Unlit | Texture" In the right part of the properties, click on the square with the image of the “Texture box” texture, from the list that appears, select the texture of our background (or you can simply drag the texture file here from the “Project” zone). In the property " Tiling» enter the values ​​x = 25 , y = 25 .



10. In the “Hierarchy” zone, select the “Background” object. In its properties, under the component " Mesh Renderer» open « Materials" and change the value " Element 0"on our material" BackgroundMaterial».


After this, a full-fledged background will appear on the game scene. We now know that a background is just a small image converted to material, stretched over a flat figure in the background.

3.3. Creating a script

In order to make game objects move, we need scripts. Scripts are a kind of logical commands that instruct objects how to behave in a given situation. In Unity you can write scripts in the following programming languages: C#, Boo, UnityScript. We will use the C# language as it belongs to the series of the most popular programming languages.

(Even if you don’t know any programming language, you can simply repeat all the steps we described step by step. The language commands are logical and become intuitive over time. Later, you can use and transform the created lines of code at your discretion, without even understanding them internal mechanisms. The main thing is to start doing this, and understanding the principles of programming will come with experience).


Implementation of player movements

1. In the “Project” area, right-click on the folder “ Scripts", in the drop-down list select " Create» - « C# Script" (Or you can click on the “Create” button in the upper left corner of the area and create a script there). Let's name the created file - " PlayerScript».



2. Double-click on the script file, after which the window of the additional program “MonoDevelop” will open (this is a program from the Unity kit designed for writing scripts).


After launching “MonoDevelop” we see that part of the program code has already been created automatically. We are not changing anything for now, but are studying what appears in the code by default.


Consider a standard script template

At the very top we see two lines:

using UnityEngine;
using System.Collections.Generic;

In the program code we must operate different classes objects. Class descriptions are contained in special libraries. We connect these libraries to our code with the “using” command.

The UnityEngine library contains descriptions of all standard objects inside the Unity engine (objects, their properties, files, prefabs, inheritance system, connections between objects).

The “System.Collections.Generic” library contains the simplest logical structures (classes, lists, lists, arrays, tables, vectors), as well as sources of external data for our future game(pressing keyboard keys, mouse buttons, screen properties).


public class PlayerScript: MonoBehaviour (

This is the title of the script we created. Note that the third word "PlayerScript" is the name of the script, which corresponds to how we named the file "PlayerScript.cs". After the colon, the class of our script is indicated - “MonoBehaviour”. This is a standard class for all Unity scripts.

After the “(” symbol, the list of commands inside the script begins. In the very last line, the script must end with the “)” symbol.


Inside the script we see the lines:

// Use this for initialization

void Update() (

These are two empty standard functions. "void" is a command to call a function. “Start” and “Update” are the names of the functions.

“()” means that this is a procedural function, it does not need external values, and it does not produce a result, but simply performs certain actions.

“()” - the beginning and end boundaries of functions; between these symbols there should be lines of function, but for now it is empty. You see, we have the boundaries of the entire script, and within it there are the boundaries of two functions. In particularly large scripts, the number of “()” symbols starts to dazzle your eyes, and you need to carefully monitor where you insert lines of code.

Before the functions we see lines of text starting with the characters “//”. This is how comments to the program code are indicated. These entries do not affect the code itself in any way, but they help you understand it. In the code itself, you cannot use Russian even for naming variables, but in the comments we can write anything we want in any language.


Changing the script

3. The line “using System.Collections;” We change it to get more opportunities during development. Add the “.Generic” subcategory:

using System.Collections.Generic ;

4. The “Start” function is executed once when an object is created in the game, and the “Update” function is repeated every moment during the game. We don’t need “Start”, we can delete it.


5. Let's create the variable values ​​that we will need. After the line “public class PlayerScript: MonoBehaviour (” add the following text:

// Changing the hero's movement speed
public float playerSpeed ​​= 2.0f;

// Current moving speed
private float currentSpeed ​​= 0.0f;

// Create variables for the buttons
public List upButton;
public List downButton;
public List leftButton;
public List rightButton;

// Save last move
private Vector3 lastMovement = new Vector3();

Let's look at what we wrote. In the first line:

“public” is a public type of variable (it can be changed by other game objects).

“float” is the type of value stored in a variable, in this case a number with a fractional value.

“playerSpeed” is the name of the variable (you can name it differently).

"= 2.0f" is the initial value stored in the variable. A fractional number is written in this format - a number with a dot, and at the end the letter “f”, so that the computer understands that this is not an ordinary number, but a number with a fractional value. This type of variable is used for the coordinates of an object in space.


The remaining lines are written according to the same principle, but they have slightly different variable values:

“private” is a private type of variable (such a variable can only be changed by the object itself, a variable for internal use).

"List " - variable type "array of several values", the array contains references to keyboard keys. “upButton”, “downButton”,.. – names of the keys used.

“Vector3” is a type of variable “vector in three dimensions”. “new Vector3()” - creating an empty vector (required to initialize this type of variable).


Linking the script to the object

6. Save the changes in the script. We can do this by pressing the key combination “Ctrl + S”. We minimize the “MonoDevelop” window and return to the Unity screen.


7. In the “hierarchy” select the ship object. Drag the script file into the ship properties into the “inspector” window. A new object property “Player Script (Script)” will appear there. Here we can see that all public variables are displayed in the properties of the object, and we can change them directly from here without having to go back to the program code.



8. Let's set up the control of our ship. In the properties of each button variable “Up Button”, “Down Button”, “Left Button”, “Right Button” in the line “ Size" set the value " 2 " After this, two lists “Element 0” and “Element 1” appear, in them we select the keys that will correspond to this variable. For "Up Button" it is " UpArrow" (up arrow key on keyboard) and " W" As a result, we must assign everything to variables arrow buttons and the keys " W, A, S, D", as shown in the figure. (Once you open the list, you can press the key with the first letter of the key name on your keyboard to quickly find it in the huge list).

Thus, the movement control will be duplicated on both the arrow keys and the letter keys, and the player will choose what to use.


Writing functions for moving an object

9. Return to “MonoDevelop”. Inside the “Update” function we write two more functions. Placing functions in "Update" means that they will be repeated again and again throughout the game:

// Update is called once per frame
void Update() (

// Rotate the hero towards the mouse

// Move the hero

}

10. Above we only wrote a call to our functions. Now below we need to describe what these functions will actually perform. After the “)” character that closes the “Update” function, and before the last “)” character, add the code:

// Rotate the hero towards the mouse
void Rotation() (
// Show the player where the mouse is
Vector3 worldPos = Input.mousePosition;
worldPos = Camera.main.ScreenToWorldPoint(worldPos);
// Save the mouse pointer coordinates
float dx = this.transform.position.x - worldPos.x;
float dy = this.transform.position.y - worldPos.y;
// Calculate the angle between the “Ship” and “Pointer” objects
float angle = Mathf.Atan2(dy, dx) * Mathf.Rad2Deg;
// Transform the angle into a vector
Quaternion rot = Quaternion.Euler(new Vector3(0, 0, angle + 90));
// Change the hero's rotation
this.transform.rotation = rot;
}

11. We describe the movement function of the ship “Movement”:

// Movement of the hero towards the mouse
void Movement() (
// Required movement
Vector3 movement = new Vector3();
// Checking the keys pressed
movement += MoveIfPressed(upButton, Vector3.up);
movement += MoveIfPressed(downButton, Vector3.down);
movement += MoveIfPressed(leftButton, Vector3.left);
movement += MoveIfPressed(rightButton, Vector3.right);
// If several buttons are pressed, handle this
movement.Normalize();
// Check if the button is pressed
if(movement.magnitude > 0)
{
// After clicking, move in this direction
currentSpeed ​​= playerSpeed;
this.transform.Translate(movement * Time.deltaTime * playerSpeed, Space.World);
lastMovement = movement;
}
else
{
// If nothing is pressed
this.transform.Translate(lastMovement * Time.deltaTime * currentSpeed, Space.World);
// Slow down over time
currentSpeed ​​*= 0.9f;
}
}

// Returns movement if the button is pressed
Vector3 MoveIfPressed(List keyList, Vector3 Movement) (
// Check buttons from the list
foreach (KeyCode element in keyList)
{
if(Input.GetKey(element))
{
// If pressed, leave the function
return Movement;
}
}
// If the buttons are not pressed, then we do not move
return Vector3.zero;
}


12. Save the script file, return to the Unity window, save the scene (in the main menu click “ File | Save Scene" Now we can launch our game. On the " Game"Press the button " Maximize on Play"so that the game runs in the entire Unity window. Press the key " Play" at the top of the screen to enable the game. (To turn off the game, press the " key again Play»).



Great! She works! The ship rotates with the mouse pointer, and moves if we press the directional buttons. But it doesn’t look like a full-fledged game yet; now we need to add other game elements to it.

Achievement "Honorary Reader Site"
Did you like the article? As a thank you, you can like via any social network. For you this is one click, for us it is another step up in the ranking of gaming sites.
Achievement "Honorary Sponsor Site"
For those who are especially generous, there is the opportunity to transfer money to the site’s account. In this case, you can influence the choice new topic for an article or walkthrough.
money.yandex.ru/to/410011922382680
+ Add a comment


Fool