что такое sprite unity

Что такое sprite unity

Компонент 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 unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

Свойство:Функция:
SpriteСпрайт, который надо рендерить. Спрайты можно создать из текстур используя настройку Sprite в импортере текстур (Texture importer).
ColorЦвет меша, который рендерится.
FlipFlip the sprite in the X or Y planes.
MaterialМатериал, используемый для рендера спрайта.
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.

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

Flipping

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.

Источник

Работа со спрайтами (Unity3d)

Введение

Всем привет.
Вначале небольшой экскурс.
Эта статья является своеобразным переводом обучающей программы от Jesse Freeman. Ему спасибо за мою теперешнюю возможность получить инвайт. Остальным спасибо за понимание, что это моя первая статья.
В утопическом мире населенном только хабралюдьми, я постараюсь сделать так, чтобы за этой статьей последовало еще 9, но мир не идеален, так что пока не известно как всё пойдет. Вроде всё, тогда поехали.

Импортирование спрайтов

что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

Отлично, теперь перетащим спрайт игрока на сцену, и что мы видим спрайт стал gameobject’ом.
что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

Следующее свойство спрайтов о котором я расскажу называется Pixels To Units. Как вы видите спрайт игрока 80×80 пикселей, а в Unity 100×100 пикселей соответствуют одному квадратному метру, поэтому перейдя к настройкам импорта спрайта в строке Pixels To Units вы увидите значение 100 и это означает, что спрайт отображается корректно.Давайте изменим значение на 80, в таком случае вы увидите, что спрайт игрока увеличился, теперь он занимает равно один юнит квадратный.

что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

Примечание от переводчика для более корректного отображения спрайтов рекомендуется использовать в этом поле значение 100.

Следующее свойство спрайтов о котором я расскажу называется Pivot. Если кратко — это точка привязки. По умолчанию установлена на центр. Вы можете изменить ее в случае необходимости, но в большинстве случае привязка в центре подходит. Здесь обойдемся без иллюстраций.
Едем дальше.

Поле Filter Mode по умолчанию имеет значение Bilinear, но так как у нас Pixel Art нам нужно изменить его значение на Point, после применения изменений вы видите, что спрайт стал выглядеть лучше, но при приближении видны аномалии, для того чтобы избавиться от них изменим значение поля Format на TrueColor.
Теперь спрайт не имеет никаких аномалий. Запомните такие настройки, поскольку их нужно применять каждый раз при работе с Pixel Art’ом.

что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

Внимание:

что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

Возможно следующие уроки будут объемнее, а пока всё.

Источник

Sprite Editor

Sometimes a Sprite Texture contains just a single graphic element but it is often more convenient to combine several related graphics together into a single image. For example, the image could contain component parts of a single character, as with a car whose wheels move independently of the body. Unity makes it easy to extract elements from a composite image by providing a Sprite Editor for the purpose.

Note: Make sure the graphic you want to edit has its Texture Type set to Sprite (2D and UI). For information on importing and setting up Sprites, see Sprites.

Sprite Textures with multiple elements need the Sprite Mode to be set to Multiple in the Inspector. (Texture Import Inspector image below.)

Открытие редактора спрайтов

Открытие редактора спрайтов

Select the 2D image you want to edit from the Project View (Fig 1: Project View).

Note that you can’t edit a Sprite by selecting it in the Scene View.

Click on the Sprite Editor button in the Texture Import Inspector (Fig 2: Texture Import Inspector) and the Sprite Editor displays (Fig 3: Sprite Editor).

Note: You can only see the Sprite Editor button if the Texture Type on the image you have selected is set to Sprite (2D and UI).

Note: Set the Sprite Mode to Multiple in the Texture Import Inspector if your image has several elements.

что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unitySprite Editor

Along with the composite image, you will see a number of controls in the bar at the top of the window. The slider at the top right controls the zoom, while the color bar button to its left chooses whether you view the image itself or its alpha levels. The right-most slider controls the pixelation (mipmap) of the Texture. Moving the slider to the left reduces the resolution of the Sprite Texture. The most important control is the Slice menu at the top left, which gives you options for separating the elements of the image automatically. Finally, the Apply and Revert buttons allow you to keep or discard any changes you have made.

Использование редактора

The most direct way to use the editor is to identify the elements manually. If you click on the image, you will see a rectangular selection area appear with handles in the corners. You can drag the handles or the edges of the rectangle to resize it around a specific element. Having isolated an element, you can add another by dragging a new rectangle in a separate part of the image. You’ll notice that when you have a rectangle selected, a panel appears in the bottom right of the window:

что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

The controls in the panel let you choose a name for the Sprite graphic and set the position and size of the rectangle by its coordinates. A border width, for left, top, right and bottom can be specified in pixels. The borders are useful when 9-Slicing Sprites. There are also settings for the Sprite’s pivot, which Unity uses as the coordinate origin and main “anchor point” of the graphic. You can choose from a number of default rectangle-relative positions (eg, Center, Top Right, etc) or use custom coordinates.

The Trim button next to the Slice menu item will resize the rectangle so that it fits tightly around the edge of the graphic based on transparency.

Note: Borders are only supported for the UI system, not for the 2D SpriteRenderer.

Автоматическая нарезка (slicing)

Isolating the Sprite rectangles manually works well but in many cases, Unity can save you work by detecting the graphic elements and extracting them for you automatically. If you click on the Slice menu in the control bar, you will see this panel:

что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

With the slicing type set to Automatic, the editor will attempt to guess the boundaries of Sprite elements by transparency. You can set a default pivot for each identified Sprite. The Method menu lets you choose how to deal with existing selections in the window. The Delete existing option will simply replace whatever is already selected, Smart will attempt to create new rectangles while retaining or adjusting existing ones, and Safe will add new rectangles without changing anything already in place.

Grid by Cell Size or Grid by Cell Count options are also available for the slicing type. This is very useful when the Sprites have already been laid out in a regular pattern during creation:

что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

The Pixel Size values determine the height and width of the tiles in pixels. If you chose grid by cell count, Column & Row determines the number of columns and rows used for slicing. You can also use the Offset values to shift the grid position from the top-left of the image and the Padding values to inset the Sprite rectangles slightly from the grid. The Pivot can be set with one of nine preset locations or a Custom Pivot location can be set.

Note that after any of the automatic slicing methods has been used, the generated rectangles can still be edited manually. You can let Unity handle the rough definition of the Sprite boundaries and pivots and then do any necessary fine tuning yourself.

Polygon Resizing

Open the Sprite Editor for a polygon and you have the option to change its shape, size, and pivot position.

Polygon shape

Enter the number of sides you want the polygon to have in the Sides field and click Change.

Polygon size and pivot

Polygon size

To change the polygon’s size, click on the Sprite to display green border lines and the Sprite information box. Click and drag on the green lines to create the border you want, and the values in the Border fields change.

Polygon pivot

To change the polygon’s pivot point (that is the axis point the polygon moves around), click on the image to display the Sprite information box. Click on the Pivot drop down menu and select an option. This displays a blue pivot circle on the polygon; its location depends on the pivot option to you have selected. If you want to change it further, select Custom Pivot and click and drag on the blue pivot circle to position it.

Источник

Sprites

Sprites are 2D Graphic objects. If you are used to working in 3D, Sprites are essentially just standard textures but there are special techniques for combining and managing sprite textures for efficiency and convenience during development.

See Importing and Setting up Sprites below for information on setting up assets as Sprites in your Unity project.

Sprite Tools

Sprite Creator

Use the Sprite Creator to create placeholder sprites in your project, so you can carry on with development without having to source or wait for graphics.

Sprite Editor

The Sprite Editor lets you extract sprite graphics from a larger image and edit a number of component images within a single texture in your image editor. You could use this, for example, to keep the arms, legs and body of a character as separate elements within one image.

Sprite Renderer

Sprites are rendered with a Sprite Renderer component rather than the Mesh Renderer used with 3D objects. Use it to display images as Sprites for use in both 2D and 3D scenes.

Sprite Packer

Use Sprite Packer to opimize the use and performance of video memory by your project.

Importing and Setting Up Sprites

Sprites are a type of Asset in Unity projects. You can see them, ready to use, via the Project view.

There are two ways to bring Sprites into your project:

In your computer’s Finder (Mac OS X) or File Explorer (Windows), place your image directly into your Unity Project’s Assets folder.

Unity detects this and displays it in your project’s Project view.

In Unity, go to Assets > Import New Asset to bring up your computer’s Finder (Mac OS X) or File Explorer (Windows).

From there, select the image you want, and Unity puts it in the Project view.

See Importing for more details on this and important information about organising your Assets folder.

Setting your Image as a Sprite

If your project mode is set to 2D, the image you import is automatically set as a Sprite. For details on setting your project mode to 2D, see 2D or 3D Projects.

However, if your project mode is set to 3D, your image is set as a Texture, so you need to change the asset’s Texture Type:

For details on Sprite Texture Type settings, see Texture type: Sprite (2D and UI).

Sorting Sprites

Renderers in Unity are sorted by several criteria, such as their Layer order or their distance from the Camera. Unity’s GraphicsSettings (menu: Edit > Project Settings, then select the Graphics category) provide a setting called Transparency Sort Mode, which allows you to control how Sprites are sorted depending on where they are in relation to the Camera. More specifically, it uses the Sprite’s position on an axis to determine which ones are transparent against others, and which are not.

An example of when you might use this setting is to sort Sprites along the Y axis. This is quite common in 2D games, where Sprites that are higher up are sorted behind Sprites that are lower, to make them appear further away.

что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

There are four Transparency Sort Mode options available:

что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

    If you have set the Transparency Sort Mode to Custom, you then need to set the Transparency Sort Axis:

    что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

    If the Transparency Sort Mode is set to Custom Axis, renderers in the Scene view are sorted based on the distance of this axis from the camera. Use a value between –1 and 1 to define the axis. For example: X=0, Y=1, Z=0 sets the axis direction to up. X=1, Y=1, Z=0 sets the axis to a diagonal direction between X and Y.

    For example, if you want Sprites to behave like the ones in the image above (those higher up the y axis standing behind the Sprites that are lower on the axis), set the Transparency Sort Mode to Custom Axis, and set the Y value for the Transparency Sort Axis to a value higher than 0.

    Sorting Sprites using script

    You can also sort Sprites per camera through scripts, by modifying the following properties in Camera:

    TransparencySortMode (corresponds with Transparency Sort Mode)

    TransparencySortAxis (corresponds with Transparency Sort Axis)

    2018–04–25 Page amended with limited editorial review

    2017–05–24 Page amended with no editorial review

    Источник

    Sprites

    Sprites are 2D Graphic objects. If you are used to working in 3D, Sprites are essentially just standard textures but there are special techniques for combining and managing sprite textures for efficiency and convenience during development.

    Unity provides a placeholder Sprite Creator, a built-in Sprite Editor, a Sprite Renderer A component that lets you display images as Sprites for use in both 2D and 3D scenes. More info
    See in Glossary and a Sprite Packer A facility that packs graphics from several sprite textures tightly together within a single texture known as an atlas. Unity provides a Sprite Packer utility to automate the process of generating atlases from the individual sprite textures. More info
    See in Glossary

    See Importing and Setting up Sprites below for information on setting up assets as Sprites in your Unity project.

    Sprite Tools

    Sprite Creator

    Use the Sprite Creator to create placeholder sprites in your project, so you can carry on with development without having to source or wait for graphics.

    Sprite Editor

    The Sprite Editor lets you extract sprite graphics from a larger image and edit a number of component images within a single texture in your image editor. You could use this, for example, to keep the arms, legs and body of a character as separate elements within one image.

    Sprite Renderer

    Sprite Packer

    Use Sprite Packer to optimize the use and performance of video memory by your project.

    Importing and Setting Up Sprites

    Sprites are a type of Asset Any media or data that can be used in your game or project. An asset may come from a file created outside of Unity, such as a 3D Model, an audio file or an image. You can also create some asset types in Unity, such as an Animator Controller, an Audio Mixer or a Render Texture. More info
    See in Glossary in Unity projects. You can see them, ready to use, via the Project In Unity, you use a project to design and develop a game. A project stores all of the files that are related to a game, such as the asset and Scene files. More info
    See in Glossary view.

    There are two ways to bring Sprites into your project:

    In your computer’s Finder (Mac OS X) or File Explorer (Windows), place your image directly into your Unity Project’s Assets folder.

    Unity detects this and displays it in your project’s Project view.

    In Unity, go to Assets > Import New Asset to bring up your computer’s Finder (Mac OS X) or File Explorer (Windows).

    From there, select the image you want, and Unity puts it in the Project view.

    See Importing for more details on this and important information about organising your Assets folder.

    Setting your Image as a Sprite

    If your project mode is set to 2D, the image you import is automatically set as a Sprite. For details on setting your project mode to 2D, see 2D or 3D Projects.

    For details on Sprite Texture Type settings, see Texture type: Sprite (2D and UI).

    Sorting Sprites

    An example of when you might use this setting is to sort Sprites along the Y axis. This is quite common in 2D games, where Sprites that are higher up are sorted behind Sprites that are lower, to make them appear further away.

    что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

    There are four Transparency Sort Mode options available:

    что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

      If you have set the Transparency Sort Mode to Custom, you then need to set the Transparency Sort Axis:

      что такое sprite unity. Смотреть фото что такое sprite unity. Смотреть картинку что такое sprite unity. Картинка про что такое sprite unity. Фото что такое sprite unity

      If the Transparency Sort Mode is set to Custom Axis, renderers in the Scene view An interactive view into the world you are creating. You use the Scene View to select and position scenery, characters, cameras, lights, and all other types of Game Object. More info
      See in Glossary are sorted based on the distance of this axis from the camera. Use a value between –1 and 1 to define the axis. For example: X=0, Y=1, Z=0 sets the axis direction to up. X=1, Y=1, Z=0 sets the axis to a diagonal direction between X and Y.

      For example, if you want Sprites to behave like the ones in the image above (those higher up the y axis standing behind the Sprites that are lower on the axis), set the Transparency Sort Mode to Custom Axis, and set the Y value for the Transparency Sort Axis to a value higher than 0.

      Sorting Sprites using script

      TransparencySortMode (corresponds with Transparency Sort Mode)

      TransparencySortAxis (corresponds with Transparency Sort Axis)

      Источник

      Добавить комментарий

      Ваш адрес email не будет опубликован. Обязательные поля помечены *