The book "Unity for the developer. Mobile multiplatform games »

6. Implementation of the gameplay with traps and targets
Simple traps
Most of this game is to handle the touches of various objects - traps, treasures, exit points, etc. Given how important it is to determine when a particular object touches, let's create a common scenario that generates a Unity Event when any object with the “Player” tag touches them. This event will then be configured differently for different objects: the traps will inform the Game Manager game manager that the gnome was damaged, the treasure will report that the gnome picked up the treasure, and the exit point that the gnome reached the exit.
Now create a new C # script in a file called SignalOnTouch.cs and add the following code to it:
using UnityEngine.Events;
// Вызывает UnityEvent, когда объект с тегом "Player" касается// данного объекта.
[RequireComponent (typeof(Collider2D))]
publicclassSignalOnTouch : MonoBehaviour {
// UnityEvent для выполнения в ответ на касание.
// Вызываемый метод подключается в редакторе.public UnityEvent onTouch;
// Если имеется значение true, при касании проигрывается звук из AudioSource.publicbool playAudioOnTouch = true;
// Когда обнаруживается вход в область действия триггера,
// вызывается SendSignal.voidOnTriggerEnter2D(Collider2D collider) {
SendSignal (collider.gameObject);
}
// Когда обнаруживается касание с данным объектом, // вызывается SendSignal.voidOnCollisionEnter2D(Collision2D collision) {
SendSignal (collision.gameObject);
}
// Проверяет наличие тега "Player" у данного объекта и
// вызывает UnityEvent, если такой тег имеется.
voidSendSignal(GameObject objectThatHit) {
// Объект отмечен тегом "Player"?if (objectThatHit.CompareTag("Player")) {
// Если требуется воспроизвести звук, попытаться сделать это
if (playAudioOnTouch) {
var audio = GetComponent<AudioSource>();
// Если имеется аудиокомпонент
// и родитель этого компонента активен,
// воспроизвести звук
if (audio &&
audio.gameObject.activeInHierarchy)
audio.Play();
}
// Вызвать событие
onTouch.Invoke();
}
}
}
The basis of the SignalOnTouch class is the SendSignal method, which is called by the OnCollisionEnter2D and OnTriggerEnter2D methods. The last two methods are triggered by the Unity engine when an object touches a collider or when an object enters the scope of a trigger. The SendSignal method checks the object tag and, if it stores the string “Player”, generates a Unity event.
Now that you have the SignalOnTouch class, you can add the first trap.
1. Import sprites of objects. Import the contents of the Sprites / Objects folder into the project.
2. Add brown spikes. Locate the SpikesBrown sprite and drag it into the scene.
3. Set up an object with spikes. Add the components PolygonCollider2D and SignalOnTouch to the spiked object.
Add a new function to the SignalOnTouch event. Drag the Game Manager into the object field and select the GameManager.TrapTouched function, as shown in Figure. 6.1.

4. Convert the spiked object into a template. Drag the SpikesBrown object from the Hierarchy panel to the Level folder. As a result, a template will be created with which you can create multiple copies of the object.
5. Test it. Run the game. Make the gnome fall on the spikes. This gnome should fall and reappear!
Treasure and exit
After successfully adding the trap that kills the gnome, it's time to add the opportunity to win the game. To do this, add two new elements: the treasure and the exit point.
The treasure is a sprite at the bottom of the well that detects the touch of the gnome and sends a signal to the game manager's game manager. When this happens, the game dispatcher informs the gnome that he grabbed the treasure, after which the sprite with the image of the empty hand of the gnome is replaced with the sprite with the image of the hand holding the treasure.
The exit point is another sprite at the top of the well. Like a treasure, he discovers the touch of the gnome and notifies the game controller of this. If at this moment the gnome holds the treasure, the player is awarded a victory in the game.
The main work in these two objects is performed by the SignalOnTouch component - when the gnome reaches the exit point, the ExitReached method of the game manager should be called, and when the gnome touches the treasure, the TreasureCollected method should be called.
Start by creating an exit point, and then add treasure.
Creating an exit point
First of all, we import sprites.
1. Import Level Background Sprites. Copy the Sprites / Background folder from the downloaded resource package to the project's Sprites folder.
2. Add Sprite Top. Place it just below the Rope object. This sprite will serve as an exit point.
3. Configure the sprite. Add the Box Collider 2D component to the sprite and check the Is Trigger box. Click the Edit Collider button and edit the dimensions of the collider to make it short and wide, as shown in Figure. 6.2.

4. Configure sending a signal to the game dispatcher when the sprite is touched. Add the SignalOnTouch component to the sprite. Add an item to the component's event list and connect it to the Game Manager. Select the GameManager.ExitReached function. Now touching the exit point gnome will call the Game Manager's ExitReached method.
Now add the treasure.
The treasure works like this: by default, the Treasure object displays a sprite with a treasure image. When the gnome touches him, the TreasureCollected method of the Game Manager is called and a different sprite is displayed at the treasure site, indicating that the treasure has been selected. When the gnome dies, the Treasure object returns to its original state and again displays the sprite with the image of the treasure.
Since the change of sprites in the game will be performed quite often - you will see this when we improve graphics, it makes sense to create a universal class for changing sprites and use it in the treasure object.
Create a new C # script called SpriteSwapper.cs. Add the following code to it:
// Меняет один спрайт на другой. Например, при переключении сокровища// из состояния 'сокровище есть' в состояние 'сокровища нет'.publicclassSpriteSwapper : MonoBehaviour {
// Спрайт, который требуется отобразить.public Sprite spriteToUse;
// Визуализатор спрайта, который должен использоваться // для отображения нового спрайта.public SpriteRenderer spriteRenderer;
// Исходный спрайт. Используется в вызове ResetSprite.private Sprite originalSprite;
// Меняет спрайт.
publicvoidSwapSprite() {
// Если требуемый спрайт отличается от текущего...
if (spriteToUse != spriteRenderer.sprite) {
// Сохранить предыдущий в originalSprite
originalSprite = spriteRenderer.sprite;
// Передать новый спрайт визуализатору.
spriteRenderer.sprite = spriteToUse;
}
}
// Возвращает прежний спрайт.
publicvoidResetSprite() {
// Если прежний спрайт был сохранен...
if (originalSprite != null) {
// ...передать его визуализатору.
spriteRenderer.sprite = originalSprite;
}
}
}
The SpriteSwapper class is designed for two operations: when the SwapSprite method is called, another Sprite is passed to the SpriteRenderer visualizer connected to the game object for display. In this case, the original sprite is stored in a variable. When the ResetSprite method is called, the original sprite is rendered for rendering to the visualizer.
Now you can create and set up a Treasure object.
1. Add a sprite with a treasure image. Find the TreasurePresent sprite and add it to the scene. Place it closer to the bottom, but in such a way that the gnome can reach it.
2. Add a collider for treasure. Select a sprite with a treasure image and add the Box Collider 2D component to it. Check the box for Is Trigger.
3. Add and customize the sprite shift script. Add a SpriteSwapper component. Drag the sprite with the treasure image itself into the Sprite Renderer field of this component. Then find the TreasureAbsent sprite and drag it into the Sprite To Use field of the component that is performing the sprite changer.
4. Add and configure the send signal component in response to the touch. Add the SignalOnTouch component. Add two items to the On Touch list:
- first link to the Game Manager object and select the GameManager.TreasureCollected method;
- second, link the treasure to the sprite (that is, the object you are setting up now) and select the SpriteSwapper.SwapSprite method.
5. Add and configure the Resettable component. Add a Resettable component to the object. Add a single item to the On Touch list, select the SpriteSwapper.ResetSprite method and associate it with the Treasure object.
As a result, the settings in the inspector panel should look like the one shown in fig. 6.3.
6. Test the game. Start the game and tap the treasure. At this moment the treasure will disappear; if after this the dwarf dies, the treasure will reappear in its place after the creation of a new dwarf.
Add background
Currently, the action of the game takes place on a dull blue background, set in Unity by default. In this section, we will add a temporary background, which we will replace with the background sprite when we begin to improve the graphic design of the game.
1. Add a background rectangle. Open the GameObject menu (Game Object) and select 3D ObjectQuad (3D Object Rectangle). Name the new object Background.
2. Move the background to the background. To avoid a situation where a rectangular background will be drawn on top of the game sprites, move it to the back, away from the camera. To do this, assign the Z coordinate to the value 10.

3. Set the width and height of the background rectangle. Turn on the Rect tool by pressing the T key, and then using the handles, set the dimensions of the rectangle. The upper border of the background should be on the same level with the sprite at the top of the scene, and the lower - with the treasure (Fig. 6.4).

4. Test the game. After starting, the background of the playing field should turn dark gray.
»More information about the book is available on the publisher's website
» Table of contents
» Fragment
For Habrozhiteley 20% discount on the coupon - Unity