Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

Vytváření instancí

Poznámka

This tutorial refers to instancing scenes in the editor. To learn how to instance scenes from code, see Instance uzlů a scén.

Godot's approach to instancing described below should not be confused with hardware instancing that can be used to render large amounts of similar objects quickly. See Optimalizace pomocí MultiMeshes instead.

V předchozí části jsme si ukázali, že scéna je kolekce uzlů uspořádaných do stromové struktury s jedním kořenovým uzlem. Svůj projekt můžete rozdělit do libovolného počtu scén, což vám pomůže lépe rozčlenit a organizovat jednotlivé komponenty vaší hry.

Můžete vytvořit tolik scén, kolik chcete, a uložit je jako soubory s příponou .tscn (zkratka pro "textová scéna"). Příkladem byl soubor label.tscn z předchozí lekce. Takovéto soubory nazýváme "zabalené scény", protože obsahují informace o obsahu vaší scény.

Jako příklad si vezměme následující míč. Skládá se z kořenového uzlu RigidBody2D s názvem Míč, který mu umožňuje padat a odrážet se po stěnách, uzlu Sprite2D a uzlu CollisionShape2D.

../../_images/instancing_ball_scene.webp

Jakmile scénu uložíte, funguje jako šablona: můžete ji opakovaně vkládat do dalších scén, kolikrát chcete. Tento způsob opakovaného použití objektu na základě šablony se nazývá instancování.

../../_images/instancing_ball_instances_example.webp

Jak jsme zmínili v předchozí části, instance scén se chovají jako běžné uzly: editor ve výchozím nastavení skryje jejich vnitřní strukturu. Když tedy instancujete scénu Míč, uvidíte jen uzel s názvem Míč. Všimněte si také, že každý duplikát má jedinečný název.

Každá instance scény Míč vychází ze stejné struktury a vlastností definováných v souboru ball.tscn. Každou z nich však můžete nezávisle upravit – například změnit, jak se odráží, jak jsou těžké nebo jakoukoli vlastnost, kterou zdrojová scéna nabízí.

Praktická ukázka

Let's use instancing in practice to see how it works in Godot. We invite you to download the ball's sample project we prepared for you: instancing_starter.zip.

Extract the archive on your computer. To import it, you need the Project Manager. The Project Manager is accessed by opening Godot, or if you already have Godot opened, click on Project -> Quit to Project List (Ctrl + Shift + Q, Ctrl + Option + Cmd + Q on macOS)

In the Project Manager, click the Import button to import the project.

../../_images/instancing_import_button.webp

In the pop-up that appears navigate to the folder you extracted. Double-click the project.godot file to open it.

../../_images/instancing_import_project_file.webp

Finally, click the Import & Edit button.

../../_images/instancing_import_and_edit_button.webp

A window notifying you that the project was last opened in an older Godot version may appear, that's not an issue. Click Ok to open the project.

The project contains two packed scenes: main.tscn, containing walls against which the ball collides, and ball.tscn. The Main scene should open automatically. If you're seeing an empty 3D scene instead of the main scene, click the 2D button at the top of the screen.

../../_images/instancing_2d_scene_select.webp ../../_images/instancing_main_scene.webp

Let's add a ball as a child of the Main node. In the Scene dock, select the Main node. Then, click the link icon at the top of the scene dock. This button allows you to add an instance of a scene as a child of the currently selected node.

../../_images/instancing_scene_link_button.webp

Double-click the ball scene to instance it.

../../_images/instancing_instance_child_window.webp

Koule se zobrazí v levém horním rohu okna zobrazení.

../../_images/instancing_ball_instanced.webp

Click on it and drag it towards the center of the view.

../../_images/instancing_ball_moved.webp

Play the game by pressing F5 (Cmd + B on macOS). You should see it fall.

Now, we want to create more instances of the Ball node. With the ball still selected, press Ctrl + D (Cmd + D on macOS) to call the duplicate command. Click and drag to move the new ball to a different location.

../../_images/instancing_ball_duplicated.webp

Tento postup můžete opakovat, dokud jich na scéně nebude několik.

../../_images/instancing_main_scene_with_balls.webp

Play the game again. You should now see every ball fall independently from one another. This is what instances do. Each is an independent reproduction of a template scene.

Úpravy scén a instancí

There is more to instances. With this feature, you can:

  1. Change the properties of one ball without affecting the others using the Inspector.

  2. Change the default properties of every Ball by opening the ball.tscn scene and making a change to the Ball node there. Upon saving, all instances of the Ball in the project will see their values update.

Poznámka

Changing a property on an instance always overrides values from the corresponding packed scene.

Let's try this. Double-click ball.tscn in the FileSystem to open it.

../../_images/instancing_ball_scene_open.webp

In the Scene dock on the left, select the Ball node. Then, in the Inspector on the right, click on the PhysicsMaterial property to expand it.

../../_images/instancing_physics_material_expand.webp

Set its Bounce property to 0.5 by clicking on the number field, typing 0.5, and pressing Enter.

../../_images/instancing_property_bounce_updated.webp

Play the game by pressing F5 (Cmd + B on macOS) and notice how all balls now bounce a lot more. As the Ball scene is a template for all instances, modifying it and saving causes all instances to update accordingly.

Let's now adjust an individual instance. Head back to the Main scene by clicking on the corresponding tab above the viewport.

../../_images/instancing_scene_tabs.webp

Select one of the instanced Ball nodes and, in the Inspector, set its Gravity Scale value to 10.

../../_images/instancing_property_gravity_scale.png

A grey "revert" button appears next to the adjusted property.

../../_images/instancing_property_revert_icon.png

Všimněte si, že vedle upravené vlastnosti se zobrazí šedé tlačítko „obnovit“. Je-li toto tlačítko k dispozici, znamená to, že jste v instanci scény upravili vlastnost originální scény tj tak, aby přepsala svoji hodnotu v uložených vlastnostech upravené scény. I když je tato vlastnost modifikována ve scéně původni, zde v instanci zůstane hodnota upravená . Stisknutím tlačítka pro obnovení vrátíte vlastnost na hodnotu v uložené scéně.

Rerun the game and notice how this ball now falls much faster than the others.

Poznámka

You may notice you are unable to change the values of the PhysicsMaterial of the ball. This is because PhysicsMaterial is a resource, and needs to be made unique before you can edit it in a scene that is linking to its original scene. To make a resource unique for one instance, right-click on the Physics Material property in the Inspector and click Make Unique in the context menu.

Resources are another essential building block of Godot games we will cover in a later lesson.

Scene instances as a design language

Instances and scenes in Godot offer an excellent design language, setting the engine apart from others out there. We designed Godot around this concept from the ground up.

We recommend dismissing architectural code patterns when making games with Godot, such as Model-View-Controller (MVC) or Entity-Relationship diagrams. Instead, you can start by imagining the elements players will see in your game and structure your code around them.

Například takhle by se dala představit jednoduchá střílečka:

../../_images/instancing_diagram_shooter.png

You can come up with a diagram like this for almost any type of game. Each rectangle represents an entity that's visible in the game from the player's perspective. The arrows point towards the insantiator of each scene.

Once you have a diagram, we recommend creating a scene for each element listed in it to develop your game. You'll use instancing, either by code or directly in the editor, to build your tree of scenes.

Hodně času stráveného při programováním her (nebo softwaru obecně) je o navrhování architektury a přizpůsobení herních komponent této architektuře. Navrh založený na scénách nahrazuje tento přístup a dělá vývoj mnohem rychlejším a přímočarějším, což vám umožňuje soustředit se na samotnou herní logiku. Protože většina herních komponent je mapována přímo na scénu, použití designu založeného na instancích scén znamená, že žádné další rozšiřování architektury kódem není většinou potřeba.

Podívejme se na další příklad hry typu otevřený-svět se spoustou zdrojů a vnořených prvků:

../../_images/instancing_diagram_open_world.png

Imagine we started by creating the room. We could make a couple of different room scenes, with unique arrangements of furniture in them. Later, we could make a house scene that uses multiple room instances for the interior. We would create a citadel out of many instanced houses and a large terrain on which we would place the citadel. Each of these would be a scene instancing one or more sub-scenes.

Později bychom mohli vytvořit scény, které představují Stráže (a další NPC) a také je přidat do Citadely. V důsledku toho by byli nepřímo přidáni do celého herního světa.

S Godotem je snadné takto postupně budovat vaši hru, protože vše, co musíte udělat, je vytvořit další scény a následně jejich instance. Kromě toho je uživatelské rozhraní editoru navrženo tak, aby bylo uživatelsky přívětivé pro programátory i neprogramátory. Typický proces týmového vývoje může vyžadovat 2D nebo 3D umělce, návrháře úrovní, herní návrháře a animátory, všechny pracující s jedním editorem.

Shrnutí

Instancing, the process of producing an object from a blueprint, has many handy uses. With scenes, it gives you:

  • Možnost rozdělit hru na opakovaně použitelné komponenty.

  • A tool to structure and encapsulate complex systems.

  • A language to think about your game project's structure in a natural way.