Как сделать спрайт для unity

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

Введение

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

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

Как сделать спрайт для unity

Как сделать спрайт для unity

Как сделать спрайт для unity

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

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

Как сделать спрайт для unity

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

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

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

Как сделать спрайт для 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.

Как сделать спрайт для unityFig 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

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

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

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

Источник

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.

Как сделать спрайт для unityFig 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

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

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

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

Источник

Unity 2D: работа со спрайтами в разных разрешениях дисплея

Как сделать спрайт для unity
Начиная с версии 4.3 в Unity появилась возможность работы с 2D графикой, большая часть новых стандартных решений мне пришлись по душе, потому что я как раз незадолго до этого обновления перешел с Corona SDK.
Но что меня не порадовало, так это отсутствие стандартных инструментов для оптимизации спрайтов под разные разрешения экранов, что имеет довольно таки существенное влияние на производительность на маломощных устройствах.

Конечно, можно использовать что-то похожее на 2D Toolkit для решения этой проблемы, но зачем платить 75$ если можно сделать все самому?

Cо слов пользователей официального форума Unity, разработчики в скором времени не планируют расширять 2D функционал, по крайней мере до релиза 5 версии Unity, и пока что пользователи должны самостоятельно решать данную проблему. Бороздя просторы интернета в надежде найти ответ, я набрел на интересный доклад одного из разработчиков Unity на летней Nordic Game Conference 2014, название говорит само за себя «2D issues and how to solve them». Пользуясь материалами этого доклада, я сделал свое решение проблемы поддержки дисплеев разного разрешения.

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

Итак, на первом этапе мы должны организовать атласы спрайтов для разных разрешений: SD, HD, ultra-HD, у нас же будут использованы суффиксы 1x, 2x, 4x.

Берем атлас спрайтов, в нашем случае это ’spritesheet1@4x.png’, в инспекторе выбираем нужные параметры, режем атлас в Sprite Editor, если требуется. Создаем еще две копии атласа в Project Browser (cmd+D, ctrl+D) и переименуем их так, чтобы суффиксы в названии были ‘@2x’, ‘@1x’, меняем свойство Max Size на значение в 2 и в 4 раза меньше соответственно.

Спрайты должны находится в папке Resources, если таковой не имеется — создайте. Это позволяет загружать файлы с этой папки во время выполнения программы.

Как сделать спрайт для unity

Как сделать спрайт для unity

Обращу Ваше внимание на поля Pixels Per Unit и Format, первое поможет подобрать размер спрайтов под размеры сцены без изменения scale, а второе является очень важным для правильной передачи цвета, размера билда и использования ресурсов графического процессора. На эту тему есть замечательный мануал

Тут все просто, мы собираем игровой объект на основе атласа спрайтов с суффиксом ‘@2x’, добавляем анимацию и любые другие фишки, которые могут вам понадобится. Сохраняем объект как префаб.
Суффикс ‘@2x’ был выбран, потому что большая часть устройств имеют hd разрешение, нам не придется делать лишнюю работу в большинстве случаев.

Скрипт будет работать с любым количеством компонентов SpriteRenderer. Он не будет влиять ни на анимацию, ни на что другое, главное чтобы имена спрайтов в атласе и SpriteRenderer`е были одинаковыми. Данную особенность можно применять не только для смены разрешения спрайтов, но и для замены их на полностью другие, например при создании другого скина персонажа.

Основной принцип работы скрипта таков: у нас есть публичная переменная spriteSheet, в которой мы передаем имя атласа, в котором находятся спрайты нашего объекта.

Как сделать спрайт для unity

С помощью метода GetQuality узнаем с каким дисплеем мы имеем дело (для моих целей было достаточно ориентироваться на высоту экрана).

Потом в методе ManageQuality, имея данные о разрешении экрана, загружаем в массив sprites все спрайты нужного нам атласа с правильным суффиксом. В массив renderers загружаем все компоненты SpriteRenderer, которые находятся в объекте. Ищем в массиве sprites спрайт по имени и присваиваем его спрайту компонента SpriteRenderer, если такой существует. Завершает все Resources.UnloadUnusedAssets (), этот метод выгружает из памяти неиспользуемые ассеты.

Также этот скрипт можно использовать для изменения всех спрайтов в сцене. Для этого создаем новый объект, например SpriteManager, и добавляем к нему данный скрипт, но с измененным определением массива renderers:

Спасибо за внимание, надеюсь статья была вам полезна.

Источник

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

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