unity что такое спрайт

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 Assets 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.

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:

Click on the asset to see its Import Inspector.

Set the Texture Type to Sprite (2D and UI).

(See Fig 1: Set Texture Type….)

See 2D or 3D Projects for details on setting your project mode to 2D.

unity что такое спрайт. Смотреть фото unity что такое спрайт. Смотреть картинку unity что такое спрайт. Картинка про unity что такое спрайт. Фото unity что такое спрайтFig 1: Set Texture Type to Sprite (2D and UI) in the asset’s inspector

Источник

Спрайты в Unity: определение, как их создавать и использовать

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

Как создать спрайт для Unity? Для этого в игровом движке предусмотрены свои инструменты, о которых мы поговорим чуть ниже.

В Unity работа со спрайтами внедрена по умолчанию, когда движок настроен на разработку 2D-игр. Если спрайт посмотреть в 3D-режиме, тогда он окажется «плоским», как лист бумаги. Все потому, что спрайт — это 2D-объект и у него нет Z-ширины.

Как создать спрайт для Unity

Когда на Unity создается новый спрайт, ему необходимо задать текстуру. Текстура — это изображение, которое отражает внешний вид спрайта. Такое изображение прикрепляется к спрайту, создавая GameObject, который можно использовать в игре.

Если нет возможности сразу добавить текстуру в проект, но наличие спрайта в игре вам обязательно, тогда можно применить «заполнитель спрайтов» на Unity. Заполнитель — это встроенный инструмент, который создает спрайт в виде простых геометрических фигур типа треугольника, квадрата, круга и заполняет их белым цветом. В дальнейшем всегда будет доступно редактирование «заполнителя».

Assets → Create → Sprites

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

Редактирование спрайтов в Unity

Создать спрайт для Unity несложно, как это делается — описано чуть выше. Вся сложность заключается в редактировании спрайта. Чем сложнее игровой спрайт и сложнее проект, тем труднее будет редактировать спрайт.

Найти кнопку «Sprite Editor». Вам откроется редактор спрайтов, в котором будет несколько доступных инструментов. Например : изменение масштаба, изменение расцветки, изменение местоположения спрайта на экране, поворот спрайта, настроить прозрачность, обрезать и др.

Средство визуализации спрайтов в Unity

Отобразить спрайт в Unity помогает компонент Sprite Renderer. Его нужно добавлять в GameObject через меню Components:

Components → Rendering → Sprite Renderer

Когда создается 3D-графика, тогда способов отразить объемный объект очень много. Например, внешний вид объекта будет зависеть от его положения на экране, освещенности, перемещения, положения камеры и др. С 2D-объектами этого всего нет.

Заключение

Как создать спрайт для Unity? Добавить спрайт в Unity несложно. Спрайт — это анимированная картинка, состоящая из множества кадров. О подготовке спрайта для Unity нужно позаботит ь ся заранее. Благо для этого есть много программ. Например:

Источник

Sprite Editor

Иногда текстура спрайта содержит только один элемент графики, но часто гораздо удобней объединить несколько изображений связанных друг с другом в одно изображение. Например, изображение может содержать составные части персонажа, как для машины колеса которой двигаются независимо от корпуса. Для этих целей Unity предоставляет Sprite Editor позволяя с легкостью извлекать элементы составного изображения.

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 Inpsector. (See Fig 2: Texture Import Inspector… 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 which is 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.

unity что такое спрайт. Смотреть фото unity что такое спрайт. Смотреть картинку unity что такое спрайт. Картинка про unity что такое спрайт. Фото unity что такое спрайтFig 3: Sprite Editor

Помимо составного изображения, вы увидите различные элементы управления в заголовке окна редактора. Слайдер в правом верхнем углу управляет приближением, в то время как кнопка с цветными полосками слева от него переключает режим отображения альфа-канала и обычный вид изображения. Самый важный элемент управления это меню Slice в левом верхнем углу, который предоставляет опции для автоматической нарезки элементов изображения. Кнопки Apply и Revert позволяют вам сохранить или отменить сделанные изменения.

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

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:

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

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

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

Shape

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

Size and Pivot

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. (Note that you cannot edit the Border fields directly.)

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. (Note that you cannot edit the Pivot fields directly.)

Источник

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

Введение

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

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

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

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

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

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

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

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

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

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

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

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

Внимание:

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

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

Источник

Sprite Creator

With this tool you can create temporary placeholder sprite (2D) graphics. You can use these in your project during development and then replace them with the graphics you want to use.

Accessing the Sprite Creator

Select Assets>Create>Sprites and then select the placeholder sprite you want to make (square, triangle, diamond, hexagon, or polygon).

unity что такое спрайт. Смотреть фото unity что такое спрайт. Смотреть картинку unity что такое спрайт. Картинка про unity что такое спрайт. Фото unity что такое спрайтAccessing the Sprite Creator

Using the Sprite

Your new placeholder sprite appears as a white shape in the asset folder you currently have open. The new sprite’s name defaults to its shape name but you have the option to rename your sprite when it is first created. If you are not sure what you want to call it, leave it as the default; you can change it later by clicking on it.

unity что такое спрайт. Смотреть фото unity что такое спрайт. Смотреть картинку unity что такое спрайт. Картинка про unity что такое спрайт. Фото unity что такое спрайтName your new sprite (or leave it to default)

You can drag and drop your placeholder sprite into the Scene View or Hierarchy to start using it in your project.

unity что такое спрайт. Смотреть фото unity что такое спрайт. Смотреть картинку unity что такое спрайт. Картинка про unity что такое спрайт. Фото unity что такое спрайтDrag and drop your placeholder sprite into Scene View

Replacing your Placeholder Sprite

To change your placeholder sprite, click on it in the Scene View and then edit via the Sprite Renderer Component in the Inspector.

unity что такое спрайт. Смотреть фото unity что такое спрайт. Смотреть картинку unity что такое спрайт. Картинка про unity что такое спрайт. Фото unity что такое спрайтReplace your sprite via the Sprite Renderer Component in the Inspector tool

Edit the Sprite field: You can click on the small circle to the right of the input field to bring up the Sprite Selector where you can browse and select from a menu of available 2D graphic assets.

unity что такое спрайт. Смотреть фото unity что такое спрайт. Смотреть картинку unity что такое спрайт. Картинка про unity что такое спрайт. Фото unity что такое спрайтSprite Selector

Источник

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

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