Game dev beginner

Purpose[]

Combining the kernelsprite with inanimate objects, living or formerly living beings is a process known as prototyping, the objects or beings become the sprite. The sprite or the individual(s) prototyped are given access to a wealth of knowledge about Sburb and their corresponding player’s personal quest, with the ability to convey the information limited by intelligence of the sprite which is limited to that of its composing parts, as seen with Jaspersprite, who struggles to convey and understand complex concepts. They are supposed to be coy in about the information, only revealing it in vague statements, riddles, or when it is deemed appropriate, however they are perfectly capable of being direct with the information as seen with Davesprite who offers to tell the alpha Dave everything. Sprites do have holes in their knowledge of Sburb, most notably in regards to the Denizens and the Choices they offer.

Along with guiding the player, they can also aid in combat, possessing the ability to create beams of energy and/or duplicate objects which can be used as an attack, heal the player and telekinetically pick up objects. The nature of their abilities is determined by the prototypings, with Nannasprite seen creating household appliances and food and healing John after a fight with ogres, Calsprite seen creating smuppets, Davesprite being able to use his stomach sword as a weapon and Becsprite appeared to be able to enhance his energy beam with his first guardian powers.

Sprites can also use their conjuration powers for non-combat purposes, as seen when Nannasprite conjured a bed and oven, when Becsprite broke Jade’s fall with a copy of her bed, and when Davesprite used his sprite powers to scribble on John’s Armageddon poster / letter. Arquiusprite also used the ability to obtain Jane’s fridge (with Gamzee Makara still inside it) during Collide. Objects summoned or created by sprites have even been used . Sprites are capable of passing through solid objects, which sometimes leaves behind ectoplasm.

A prototyped sprite, upon entering The Medium, will divide into a kernel and a sprite, and then the kernel will also divide in two, carrying the prototyping data to spires on Prospit and Derse. The data modifies the Underlings players face and the Royals of the light and dark kingdoms. Because the sprite only splits upon entering the Medium and never again, only the prototyping done before entering the Medium will affect the Underlings and Royals. (For example; John prototyped his sprite with a harlequin doll before entering the Medium, and with his grandma’s ashes after entering the Medium, but the Royals and Underlings only were affected by the harlequin prototyping.) A sprite entering the Medium also causes the the Battlefield to grow, with each entry of a prototyped sprite causing it to grow further. The final form of the Battlefield can only be reached by all players prototyping at least once before entry, as the final form of the Battlefield is required in order to grow the Genesis Frog and thus win the game.

A session with no pre-entry prototyping is called a . A lack of spires on a session’s Prospit and Derse (as well as orbs on the Queens’ rings and Kings’ scepters) are indicative of a Void session. In such cases the Kernelsprite is unaffected by entry and instead the kernel disappears upon prototyping.

Member Data Documentation

Method sprites.Sprite.eventHandlerMethod = null
protected

The method in eventHandlerObject to execute

String sprites.Sprite.eventHandlerMethodName
protected

the name of the method to handle the event

Object sprites.Sprite.eventHandlerObject = null
protected

The object to handle the event

Sprite sprites.Sprite.focusIsWith
staticprotected

INTERNAL USE ONLY This holds a reference to the Sprite that currently has the focus.

final int sprites.Sprite.HALT = 0
static

Action sprite takes at domain edges

Object sprites.Sprite.tag = null

The user can attach any object for additional sprite information

int sprites.Sprite.tagNo = 0

The user can specify an integer for additional sprite information

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

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:

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.

Политика упаковки

Упаковщик спрайтов использует packing policy, чтобы определять, как применять спрайты к атласам. Можно создавать и свои собственные правила упаковки (см. ниже), но опции Default Packer Policy и Tight Packer Policy будут всегда доступны. С этими правилами свойство Packing Tag в Texture Importer позволяет напрямую выделять атлас, для которого будет произведено упаковывание спрайтов по тегу. Т.е. все спрайты с таким же тегом упаковки будут упакованы в один и тот же атлас. Затем атласы дополнительно сортируются по признаку настройки импортирования текстур, чтобы даже в этом случае они совпадали несмотря на то, как прежде определил пользователь исходные текстуры. Если возможно, спрайты со схожей степенью сжатия текстур могут будут сгруппированы в одном и том же атласе.

  • DefaultPackerPolicy по-умолчанию будет использовать прямоугольный метод упаковывания до тех пор, пока не будет назначен “” метод в Packing Tag (т.е. назначение методу упаковывания тега приведёт к использованию плотного метода упаковывания).
  • TightPackerPolicy по-умолчанию будет использовать плотное упаковывание, если спрайт имеет плотную сетку. Если в Packing Tag будет назначен тег “”, то будет выполнен прямоугольный метод упаковки (т.е. присвоение вашему упаковыванию тега “UI_Elements” приведёт к прямоугольному методу упаковывания).
  • TightPackerPolicy по-умолчанию будет использовать плотное упаковывание, если спрайт имеет плотную сетку. Если в Packing Tag будет назначен тег “”, то будет выполнен прямоугольный метод упаковки (т.е. присвоение вашему упаковыванию тега “UI_Elements” приведёт к прямоугольному методу упаковывания).

Дополнительные материалы для изучения

  • Данный проект в скомпилированном виде channel9.msdn.com/Events/Build/2014/2-503.
  • Microsoft Virtual Academy. «Developing 2D & 3D Games with Unity for Windows» aka.ms/UnityMVA.
  • Блог Adam’s Channel 9 aka.ms/AdamChannel9.
  • Ресурсы Unity unity3d.com/learn.

Адам Тьюлипер (Adam Tuliper) — старший идеолог по технологиям в Microsoft; живет в солнечной Южной Калифорнии. Разработчик инди-игр, один из администраторов Orange County Unity Meetup и автор на pluralsight.com. Скоро в его семье появится третий ребенок, так что связывайтесь с ним, пока у него еще есть свободные минуты, по адресу [email protected] или через .

{Для верстки: в последней фамилии (литовской) есть диакритический знак, не потеряйте}

Выражаю благодарность за рецензирование статьи экспертам Мэтту Ньюмену (Matt Newman) из Subscience Studios и Тоутвидасу Цилису (Tautvydas Žilys) из Unity.

Что такое спрайт?

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

Для загрузки и отрисовки спрайтов в случай этой игры их нужно добавить в разделы “Обновление” и “Визуализация” игрового цикла. Несложно представить, что если в игре много спрайтов, то цикл довольно быстро станет большим и запутанным. В Pygame для этого есть решение: группировка спрайтов.

Набор спрайтов — это коллекция спрайтов, которые могут отображаться одновременно. Вот как нужно создавать группу спрайтов в игре:

Теперь этой возможностью можно воспользоваться, добавив группу целиком в цикл:

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

Другое

  • Атласы кешируются в Project\Library\AtlasCache.
    \t* Удаление этой папки и последующий запуск Unity приведёт к принудительной перепаковке всех атласов. Во время удаления Unity должен был закрыт.
  • Кэш атласа не подгружается при запуске.
    \t* Все текстуры должны проверяться при первой упаковке после перезапуска Unity. Сама операция может занять какое-то время, которое зависит от общего количества текстур, имеющихся в проекте.
    \t* Подгружаются только необходимые атласы.
  • Максимальный размер атласа по умолчанию равен 2048х2048.
  • При назначенном свойстве PackingTag текстуры не будут сжиматься, чтобы упаковщик спрайтов мог использовать оригинальные значения пикселей при сжатии атласов.

Polygon Resizing

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

Polygon shape

Sprite Editor: Polygon resizing — shape

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

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.

Sprite Creator

Sprite Editor: Custom Outline

How to change a Sprite from a script in Unity

To change a Sprite from a script in Unity, create a reference variable to hold the new Sprite. Then set the Sprite property of the Sprite Renderer Component on the Game Object you wish to change to match the new, replacement Sprite.

In scripting, it looks like this:

In the inspector select the new Sprite that you want to use by dragging it into the field or by using the circle select button.

Select the new Sprite by dragging it into the field or by using Circle Select.

Make sure to also set the Sprite Renderer reference in the Inspector, otherwise you’ll get an error.

Alternatively, if the script is on the same Game Object, you can easily get it by using Get Component in Start.

Then, when you want to change the Sprite, just call the Change Sprite function.

Like in this example if the Left Mouse Button is clicked:

The example will easily change a Sprite Renderer’s existing sprite to use a different one instead. But what if you want to change to one of a number of different Sprites?

What if you have multiple Sprites, such as Slices stored in a Sprite Sheet, and you want to switch to one of them, or all of them in order, or a random Sprite, all from a script?

Все дело в спрайте

Когда по умолчанию выбран режим 3D, изображения распознаются как тип Texture. Перетащить текстуру в сцену нельзя; текстура должна быть применена к какому-то объекту. Создавать 2D-игры таким путем вовсе не забавно. Я хочу просто перетаскивать изображения, чтобы они появлялись в моей сцене. Однако, если режим по умолчанию — 2D, все становится проще. Теперь, когда я перетаскиваю изображение в Unity, оно распознается как тип Sprite.

Это позволяет перетаскивать в Unity все изображения, образующие графику игры, а затем из Unity в сцену. Если какие-то изображения выглядят мелкими, то вместо их масштабирования везде, где они встречаются, вы можете просто уменьшить значение Pixels To Units. Это очень распространенная операция в Unity как для 2D, так и для 3D и обычно более производительная, чем масштабирование объектов через свойство scale преобразования.

Отпуская объекты, вы наверняка заметите, что один объект оказывается поверх другого. Unity на внутреннем уровне создает серию вершин, даже для 2D-изображений, поэтому порядок рисования может различаться в разных частях изображений. Всегда лучше явно указывать z-порядок своих изображений. Это делается одним из трех методов, перечисленных в порядке, в котором Unity рисует ваши спрайты.

  1. Вы задаете свойство Sorting Layer в Sprite Renderer.
  2. Вы задаете свойство Order in layer в Sprite Renderer.
  3. Вы задаете значение позиции по оси Z в Transform.

Уровень сортировки имеет высший приоритет, за ним следует порядок в уровне, а затем z-значение в преобразовании.

Уровни сортировки рисуются в порядке определения. Когда вы добавляете другие уровни (в Edit | Project Settings | Tags and Layers), Unity сначала рисует любой объект, который обнаруживается в уровне Default (затем учитывается Order in Layer, потом — значение позиции по оси Z в Transform), далее Background, Platforms и т. д. Поэтому вы можете легко поправить перекрытие объектов, присвоив их уровню Platforms, а объекту, который должен быть поверх, указав Order in Layer со значением 1; тогда он будет нарисован после всего, что имеет Order in Layer, равный 0.

How to change a Sprite from an array (3 examples)

Once the Sprites are assigned to the array, you can change the Sprite Renderer’s Sprite property using the same function as in . Simply pass in the name of the array and the index of the Sprite.

For example, to switch to the first Sprite in the array would look like this in scripting:

Or, if you want to switch to a random Sprite simply pass in a random number between zero and the length of the array. Like this:

Lastly, if you want to cycle through each sprite of the array, create an Integer variable to store the last Sprite index. Then increment it every time you change the Sprite:

You’ll notice in the example above that I’ve added an If Statement. This is to check if the index number has reached the end of the array. This is important as trying to retrieve a Sprite outside of the array’s range will result in an error.

Создание спрайта

Можно переходить к созданию первого спрайта. В Pygame все спрайты выступают объектами. Если вы не работали с этим типом данных в Python, то для начала достаточно знать, что это удобный способ группировки данных и кода в единую сущность. Поначалу это может путать, но спрайты Pygame — отличная возможность попрактиковаться в работе с объектами и понять, как они работают.

Начнем с определения нового спрайта:

сообщает Python, что определяется новый объект, который будет спрайтом игрока. Его тип . Это значит, что он будет основан на заранее определенном в Pygame классе .

Первое, что нужно в определении — специальная функция , включающая код, который будет запущен при создании нового объекта этого типа. Также у каждого спрайта в Pygame должно быть два свойства: и .

Первая строка, требуется в Pygame — она запускает инициализатор встроенных классов . Далее необходимо определить свойство . Сейчас просто создадим квадрат размером 50х50 и заполним его зеленым () цветом. Чуть позже вы узнаете, как сделать спрайта красивее, используя, например, персонажа или космический корабль, но сейчас достаточно сплошного квадрата.

Дальше необходимо определить спрайта. Это сокращенное от (прямоугольник). Прямоугольники повсеместно используются в Pygame для отслеживания координат объектов. Команда оценивает изображение и высчитывает прямоугольник, способный окружить его.

можно использовать для размещения спрайта в любом месте. Начнем с создания спрайта по центру:

Теперь, после определения спрайта игрока Player, нужно отрисовать (создать) его, инициализировав экземпляр (instance) класса Player. Также нужно обязательно добавить спрайт в группу .

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

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

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:

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.

Selecting Sprites based on Touches

Now you’ll work on the code to determine which sprite is selected based on the user’s current touch.

Add the implementation of to start handling taps:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
  let touch = touches.anyObject() as UITouch
  let positionInScene = touch.locationInNode(self)

  selectNodeForTouch(positionInScene) 
}

First you get the touch from the set of touches, and convert the touch coordinates to the coordinate system of the scene. With this position, you call , which you’ll implement next to select one of the animals.

Add the following helper methods to the class next:

func degToRad(degree: Double) -> CGFloat {
  return CGFloat(Double(degree) / 180.0 * M_PI)
}

func selectNodeForTouch(touchLocation: CGPoint) {
  // 1
  let touchedNode = self.nodeAtPoint(touchLocation)
  
  if touchedNode is SKSpriteNode {
    // 2
    if !selectedNode.isEqual(touchedNode) {
      selectedNode.removeAllActions()
      selectedNode.runAction(SKAction.rotateToAngle(0.0, duration: 0.1))
  
      selectedNode = touchedNode as! SKSpriteNode

      // 3
      if touchedNode.name! == kAnimalNodeName {
        let sequence = SKAction.sequence()
        selectedNode.runAction(SKAction.repeatActionForever(sequence))
      }
    }
  }
}

Sprite Kit uses radians for rotation so the first method angle given in degree to radians.

selects one of the animal sprites based on location, in three steps:

  1. First, it finds the node at the .
  2. If the node found is a instance, you first check if the node is the same as the previously selected node. In this case there is nothing to do and the method returns early. If this is a freshly selected node, then you first reset it by removing all actions on the node and then setting it back to its original, unrotated state.
  3. This if-statement checks if the selected node is one of the animatable animal nodes by checking the name property that you set. If so, you create a sequence of actions for a «wiggle» animation, like the one on the home screen when rearranging/deleting apps, and then run this sequence on the selected node. To keep the level of excitement high, you run it as an action that is repeated forever.

Build and run your code, and you should now be able to tap on the animals. When you tap them they should wiggle in a particularly cute way to show that they are selected!

Вершинная привязка

Вы можете строить миры еще быстрее с возможностью, которая называется “вершинная привязка”(Vertex snapping). Эта возможность очень проста, но является очень мощным инструментом в Unity. Она позволяет вам взять один меш за любую вершину и с помощью мышки расположить его в такое же положение вершины другого меша, который вы выберите.

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

Использовать вершинную привязку в Unity достаточно просто. Просто следуйте этим шагам:

  • Выберите меш, которым вы хотите манипулировать, и убедитесь что Transform Tool активно.
  • Нажмите и держите клавишу V для активации режима вершинной привязки.
  • Поместите курсор мыши над вершиной, которую Вы хотите использовать.
  • Зажмите левую кнопку мыши когда курсор находится над нужной вершиной, и перетащите меш к любой другой вершине на другом меше.
  • Отпустите кнопку мыши и клавишу V когда результат вас устраивает.
  • Shift-V работает как переключатель этой функциональности.
  • Вы можете привязывать вершину к вершине, вершину к поверхности, и пивот к вершине.

Навигация в окне Scene

Scene View Control Bar

Using multiple animations with events

After creating multiple animations, each with their own unique set of images, you can use events to switch between animations. Setting the animation time between 0 — 1 will ensure it stays active when using events.

Using a negative animation time disables the event actions.

Do not use negative values.

When you have set multiple animations for an object, you can use the events tab to “Change the animation (by name).” This is controlled in the “Add action” section of the condition. It will allow you to switch to the correct animation whenever the condition used in the “Add condition” section is true.

As advised before, use animation names for multiple animations in an object to easily differentiate between them.

To add an action to change animation using animation name, choose the “Change the animation (by name)” condition.

Then put that name within the “Animation name” field surrounded by quotes.

For more event details, follow the tutorials here.

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

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

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

Project ViewTexture Import Inspector with Sprite Editor button

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

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

Polygon Resizing

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

Shape

Sprite Editor: Polygon resizing — shape

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

Size and Pivot

Sprite Editor: Polygon resizing — size and pivot point — click on the polygon to display these options

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 Creator

Sprite Editor: Custom Outline

Добавляем элемент Button

Я продолжу предыдущий проект, но просто перемещу Text и Image элементы, чтобы они нам не мешали. В следующий раз мы к ним вернемся.

Итак. Уже привычным способом добавляем на канвас кнопку:

В результате этого в центре экрана получаем новенькую кнопку:

Немного много лишнего, в другой раз таки оставлю сцену пустой…

Важной особенностью этого элемента в Unity является то, что текст внутри – это уже знакомый элемент Text. Его мы разбирали

Ещё круче то, что в Button можно положить, допустим, Image, получив кнопку с картинкой.

Инспектор кнопки содержит больше элементов, чем предыдущие, но среди них есть известные компоненты, вроде Rect Transform (положение, размер) и Image (спрайт кнопки).

Из предыдущих уроков мы узнали достаточно чтобы кастомизировать кнопку на свой вкус, например так:

И да, тень и обводка работают и с кнопками.

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

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

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

Чтобы создать спрайт на Unity, пройдите по следующему пути:

Assets → Create → Sprites

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

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

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

Для редактирования спрайтов в Unity есть встроенный инструмент — Sprite Editor. Чтобы запустить редактор спрайтов, нужно:

  1. Открыть 2D-изображение в представлении проекта «Project View». Спрайт, который находится в режиме «Scene View», редактироваться не может.

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

Настройка спрайтов может происходить в ручном режиме, если вы являетесь уверенным пользователем Unity. Но можно включить автоматический режим, и движок самостоятельно позаботится о настройках вашего спрайта. Обычно автоматическое редактирование спрайта применяют в качестве «грубой» обработки. Потом все равно придется делать более тонкое редактирование «руками». Но нужно понимать, что редактирование спрайта не будет таким насыщенным, как редактирование 3D-объекта. Спрайт — это картинка.

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

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

Components → Rendering → Sprite Renderer

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

Однако важно, чтобы соблюдался приоритет между спрайтами. То есть важно определить, какой спрайт может накладываться на другой спрайт в случаях их пересечения

Sprite Renderer как раз отвечает за соблюдение приоритетности. Делается это при помощи применения технологии сортировки слоев. То есть спрайты с низким приоритетом располагаются на низших слоях и могут перекрываться спрайтами с более высоким приоритетом.

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Все про сервера
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: