Version: 2017.2
Системные требования графических функций Unity
Подборка уроков по графике

Sprite Renderer

Компонент Sprite Renderer позволяет вам отображать изображения в виде спрайтов(Sprites), чтобы использовать их и в 2D и в 3D сценах.

Add it to a GameObject via the Components menu (Component > Rendering > Sprite Renderer or alternatively, you can just create a GameObject directly with a Sprite Renderer already attached (menu: GameObject > 2D Object > Sprite).

Свойство: Функция:
Sprite Спрайт, который надо рендерить. Спрайты можно создать из текстур используя настройку Sprite в импортере текстур (Texture importer).
Color Цвет меша, который рендерится.
Flip Flip the sprite in the X or Y planes.
Material Материал, используемый для рендера спрайта.
Draw Mode Select an option from the Draw Mode drop-down box to define how the Sprite scales when you change its dimensions.
    Simple This is the default Sprite Renderer behavior. The image scales in all directions when its dimensions change.
    Sliced Use Sliced if you intend to apply 9-slicing to an image, and you want the sections to stretch. In Sliced mode, the corners stay the same size, the top and bottom of the Sprite stretch horizontally, the sides of the Sprite stretch vertically, and the centre of the Sprite stretches horizontally and vertically to fit the Sprite’s size. See documentation on 9-slicing Sprites for more information.
    Size Use this to change the horizontal and vertical size of the Sprite. You must use this to change the size of the Sprite if you want the 9-slicing to work; the default Transform component only applies a default scale.
    Tiled Use Tiled if you intend to apply 9-slicing to an image, and you want the sections to repeat. In Tiled mode, the sprite stay the same size, and does not scale. Instead, the top and bottom of the Sprite repeat horizontally, the sides repeat vertically, and the centre of the Sprite repeats in a tile formation to fit the Sprite’s size. See documentation on 9-slicing Sprites for more information.
        Size Use this to change the horizontal and vertical size of the Sprite. You must use this to change the size of the Sprite if you want the 9-slicing to work; the default Transform component only applies a default scale.
    Tile Mode When the Draw Mode is set to Tiled, use the Tile Mode property to control how the sections repeat when the dimensions of the Sprite change.
        Continuous Tile Mode is set to Continuous by default. When the size of the Sprite changes, the repeating sections repeat evenly in the Sprite.
        Adaptive When Tile Mode is set to Adaptive, the repeating sections only repeat when the dimensions of the Sprite reach the Stretch Value.
    Stretch Value Use the Stretch Value slider to set the value between 0 and 1. Note that 1 represents an image resized to twice its original dimensions, so if the Stretch Value is set at 1, the section repeats when the image is stretched to twice its original size.
Sorting Layer Слой, используемый для задачи приоритета наложения во время рендеринга.
Order In Layer Приоритет наложения спрайта в рамках его слоя. Чем ниже число, тем раньше будет рендериться спрайт, а спрайты с числами повыше, будут рисоваться поверх тех, что ниже.

Детали

В 3D графике внешний вид объекта может быть разным в соответствии с освещением и с точкой обзора на объект. А вот в 2D изображение просто отображается на экране без каких-либо трансформаций, кроме базовых перемещения, масштабирования и вращения. Позиция спрайта задаётся 2D координатами, таким образом здесь нету концепта “глубины” или расстояния от камеры.

Тем не менее, важно иметь способ определения приоритета наложения разных спрайтов(т.е, какие спрайты будут рисоваться поверх других, в случае пересечения). Например, в игре с вождением, автомобиль должен быть виден при проходе по плоским объектам на дороге. Unity использует концепт слоёв сортировки (sorting layers), чтобы позволить разделять спрайты на группы с приоритетами наложения. Спрайты, с более низким сортировочным слоем будут рисоваться под спрайтами с более высоким сортировочным слоем.

Иногда, два или более объекта в одном и том же сортировочном слое могут накладываться (например, 2 персонажа в сайд-скроллере). Свойство order in layer может быть использовано, чтобы задать приоритеты спрайтам в одном и том же слое. Так же, как и со слоями сортировки, применяется правило, что сначала рендерятся объекты с более низким значением номера и перекрываются объектами с более высоким значением. Для деталей о редактировании слоёв сортировки см.layer manager.

Рендеринг

Sprite Renderer использует текстуру указанную в свойстве Sprite, но использует шейдер и другие свойства из свойства Material (это выполняется используя за сценой MaterialPropertyBlock). Это значит, что вы можете использовать один и тот же материал для рендера разных спрайтов не трогая каждую текстуру по отдельности.

Спрайт рендерится на меше, который использует позицию, цвет и UV на каждой вершине, но у него нет вектора нормали. Если ваш материал требует векторы нормалей, то вы можете рассчитать их используя вертексный шейдер (см. Surface Shader Examples.

Стандартные шейдеры, используемые для спрайтов:

  • Sprites/Default - простой шейдер с альфа смешиванием, который не взаимодействует с освещением в сцене.

  • Sprites/Diffuse - просто шейдер поверхности с альфа смешиванием который взаимодействует с освещением. Он генерирует переднесторонний вектор нормали (0,0,–1).

Flipping

While Sprites can be flipped by setting negative transform.scale, this has the side effect of also flipping the child GameObjects and also flipping the colliders, which can be performance intensive or otherwise not preferred.

The SpriteRenderer flipping feature provides a lightweight alternative which doesn’t affect any other components or GameObjects. It simply flips the rendered sprite on x or y axis and nothing else.

Системные требования графических функций Unity
Подборка уроков по графике
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961