dragon bones анимация персонажа
Анимация в DragonBone для художников часть 1
Автор статьи: Виктория Ершова
Когда-то меня очень вдохновили работы, которые можно создать в этой программе и возможность импорта в игры была для меня интересной перспективой развития. Всегда ведь хорошо иметь «запасной аэродром» и дополнительный пункт в портфолио на случай если основная работа по какой-то причине накроется медным тазом 😀
Прежде чем вы продолжите читать, я уточню — у художников для анимации есть множество других замечательных программ (Adobe Flash/Animate, Anime Studio Pro 11 и другие), но я использовала именно DragonBone только ради саморазвития. И я хочу рассказать именно о своём методе создания анимации без профессиональных терминов. Он очень упрощён в сравнении с более стандартным использованием программы — созданием 2D анимации к играм.
Принцип создания скелетной анимации в любой программе примерно одинаков — есть слои с текстурами, полигональные сетки, вес, кости и автоматический расчёт искажения при движении из точки А в точку Б. Умея анимировать 2D в любой программе, вы быстро освоитесь в других. Даже изучить 3D анимацию будет в разы легче. Так что эти навыки и знания никогда не будут лишними!
ОБЗОР ПРОГРАММ
Для создания 2D анимации с импортом в игры профессионалы используют в основном Spine. Она профессиональная, к ней постоянно выходят обновления, есть огромное количество возможностей и многие процессы автоматизированы. Но есть один маааленький минус — цена. И я её даже вслух произносить боюсь.
Если думаете, что её можно спиратить — спешу вас огорчить. PRO версии (а смысл имеет только она) в свободном доступе сейчас НЕТ СОВСЕМ. Есть только взломанные стандартные версии, но в них отсутствует поддержка меша. А без меша смысла в программе — 0.
Для дальнейшей работы и обучения нам понадобятся две программы — Adobe Photoshop СС 2017 года и DragonBone (на данный момент у меня версия 5.6.2). Для самого рисования я дополнительно использую SAI, но пользоваться им или нет это уже ваше личное дело.
ВОЗМОЖНОСТИ СКЕЛЕТНОЙ АНИМАЦИИ С МЕШЕМ
В отличии от покадровой анимации, в скелетной не требуется отрисовывать каждый отдельный кадр — компьютер сам производит расчёты.
Обычно при упоминании скелетной анимации на ум приходят не самые красивые и довольно «деревянные» примеры, но давайте я просто покажу вам пару видео и думаю вы измените своё мнение 😉
Dragon Bones: создание 2D персонажа и скелетная, mesh-анимация
Добрый день, читатель! В этой статье рассмотрим процесс разработки типичного персонажа нашей дебютной игры Kidarian Adventures. Я продемонстрирую свою привычную структуру работы, однако, заострю внимание на создании анимации в Dragon Bones, приложу пояснения и самописные видео-туториалы.
Текущая задача: Редизайн морально устаревшей модели стандартного летающего монстра полугодовой давности. Летучая мышь не успела за нашим скилом и стала не актуальной в рамках выбранного нами графического стиля.
Модель которую будем переделывать
Как минимум, задача у нас изначально слегка упрощена: не нужно искать концепцию для персонажа, но, тем не менее, работа будет производиться практически с нулевой точки.
Этап 1: Работа с референсами
Среди людей, производящих графический контент, ничего не берется на пустом месте. Никогда не верил тем людям, которые сидя на стуле кричат: “О вдохновение!”, и начинают малевать шедевры.
И этому есть самые простые объяснения: “Черт возьми, моя мышь такая дурацкая, потому что я даже не знаю как выглядят летучие мыши! Без референсов я нарисовал просто шарик с крыльями!”.
Итак, открываем гугл и начинаем “вдохновляться” настоящими летучими мышами, строением их туловища и мордочками. Разберем строение на примере:
Определяюсь с общими формами и пропорциями. Начинаю подмечать особенности строения и крепления крыльев. Крылья представляют из себя каркас с натянутыми перепонками. Имеются маленькие ножки и большие уши. И если с туловищем все понятно (хотя в предыдущей версии я умудрился нарисовать крылья вверх ногами), то с мордой у летучих мышей все куда сложнее, и зачастую выглядят они ну… не очень.
Этап 2: Наброски
После того как определили правильную анатомию, можно приступить к визуализации. Попробовал использовать разные формы туловища, придав им слегка более гротескный вид, на подобие летающих чертей или крупных зверей. В итоге, пришел к выводу использовать изначальный план с маленьким туловищем, лапками сзади и большими крыльями.
Несколько рабочих вариантов
Краткая выдержка из процесса
Этап 2: Отрисовка/Векторизация
Этап 3. Анимация
Анимировать будем в Dragon Bones. Это бесплатный китайский аналог Spine, предоставляющий понятный интерфейс и возможности скелетной и mesh-анимации. Dragon bones распространяется бесплатно и его можно скачать с оф. сайта.
К сожалению сейчас комьюнити у данного ПО не слишком широкое, и даже на английском языке туториалов не много, в основном вся информация на китайском.
Краткая выписка происходящего на видео выше
Далее нужно преобразовать объекты в mesh, чтобы появилась возможность изменять их форму так, как нам нужно. Для этого выделяем объект на сцене, слева ставим галочку напротив mesh, после этого нажимаем Edit mesh и начинаем отрисовывать сетку таким образом, чтобы изображения нигде не искажалось и не обрезалось. Особое внимание уделяем ребрам жесткости, таким как кости в крыле, которые будут сгибаться.

UPD. Для лучшей оптимизации в игровых движках, рекомендуется делать минимум полигонов в модели. В рамках игры и летучей мыши, количество полигонов не сильно влияет на производительность, поэтому могу позволить больше
Эту операцию мы проделываем со всеми частями, которые будут морфиться. В основном это крылья и голова. Для тела будет достаточной одной только галочки mesh, сетка не требуется, так как объект будет статичен.
Когда все готово, можно прокладывать кости. Для этого используем инструмент кость (bone) в правом верху экрана. На экране всегда присутствует изначальная точка — root.
Это базовая кость, к которой по умолчанию привязана вся композиция, она является первой родительской костью. Привязки к родительским костям показаны стрелочками.
Расшифровка родительских костей
Проложив кости, нужно привязать их к мешу, для этого нажимаем кнопку Add bones to bind, выделяем все кости которые принадлежат к спрайту и жмем правой кнопкой мыши, либо по пустой части экрана, либо на Auto Generate Weight. Кости автоматически привяжутся к спрайту, им задастся значение Weight. Величина Weight или в народе “веса” отвечает, как кость влияет на спрайт. Это важно в случаях, когда к одному спрайту одновременно привязано несколько костей. Регулировка происходит при помощи ползунков, определяющих “зону ответственности” каждой кости.
Эту операцию проводим со всеми костями и спрайтами, корректируем величину weight при некорректном сгибе спрайта. Когда все кости привязаны, и отрегулированы, можно приступать непосредственно к анимированию объекта. Для этого я записал небольшое видео.
Построение ключевых кадров на примере крыла
Такая система меш анимирования подходит для всех подвижных частей нашей летучей мыши. Я доделываю тоже самое для второго крыла, слегка добавляю амплитуды для ушей и туловища.
TIPS: Некоторые моменты, которые могут прояснить работу, и то что я показал:
1. Ключевые кадры создаются автоматически, если вы сделали какое то действие с костью. (При условии что нажат соответствующий флажок)
2. С одной из последних версий в Dragon bones появились отдельные таймлайны для таких переменных как Move, Rotate и Scale. Чтобы принудительно поставить ключевую точку по одной из них, следует нажать на флажок.
3. Для того, чтобы изменять скины для персонажа, нужно добавлять спрайты в соответствующие подпапки (displays). Предварительно их нужно превратить в mesh, отрисовать сетку и привязать кости, так как делали с основными спрайтами, чтобы при той же анимации, все отображалось корректно. Чтобы добавить спрайт, просто перетаскиваем драг’н’дропом в соответствующий раздел.
Что мы получили в итоге?
Получилась несложная анимации в двух цветах.
Полученный результат мы можем выгрузить в различных форматах, которые скушает любой игровой движок.
Анимация в Dragon Bones с нуля
Спасибо за хороший видео урок!
спасибо за добрые слова. постараюсь время еще на уроки по анимации найти.
Автор, а ты пробовал программу Creature2D?
не пробовал, сейчас туторы на ютубе глянул, вроде более-менее норм. спасибо, выделю время посмотреть.
Я все делаю в DB, т.к. пока проект не приносит деньги, тратить 300 баксов жалко. По идее, если смотреть уроки, не так сложно переучиться. А пока, Кости хватает.
А ролик ваш? В смысле ваши работы и голос?
да, это мой канал. раньше там просто наработки выкладывал, портфолио, итд. а как-то после спора со Сталкашом, вернее, его фанатами, сделал ролик про геймдев и сейчас периодически стал что-то выкладывать. и дико доволен, что по dragon bones один из самых просматриваемых роликов за последние месяцы, прикладная вещь, кому-то полезная. лучше просто разговоров ни о чем.
довольно любопытно, как костями сделан псевдо-объем, я не заморачивался таким, но теперь вижу, что это довольно просто делается.
Я еще разбирался с Live 2d, но мне не нравится что у них подписка, а не покупка. И в общем, прога тоже отличная.
угу, у live2d мне интересно попробовать привязку к камере, то есть и для стримов норм, и для липсинка. по идее, может кучу времени съэкономить, если решиться 2д-анимацию делать. как-нибудь решусь.
а объем да, не сильно сложно, буквально со второго раза норм вышло. в спайне чуть удобнее итоговый риг можно сделать, ну в дб двумя костями все анимируется. для небольших проектов вполне норм.
Вот я пока и остановился. единственное, у меня бывают сцены, что слишком много объектов, все тормозит, аутлайн не слишком удобен, если честно. Я бы группы ввел, для начала. Выделение одной детали в десятке слоев тоже не всегда хорошо. Можно конечно делить сцену на несколько кусков, но это не всегда удобно. А если мне нужно несколько анимаций одной сцены?
ролик себе скачал. спс.
ну уж 2.5д и там, и там выглядит одинаково, и принцип работы тот же.
меня больше заботит интерфейсы и зависимости, т.к. в ДБ это все еще выглядит немножко. жутковато.
п.с. хотя интерфейс даже сейчас там тоже страшноват, хотя и стал лучше
Я буду испытывать еще SynFig в марте после проекта, выглядит конечно не менее жутко чем ДБ, но проект хотябы жив.
посмотрел, напоминает флеш. и ощущение, что в нем и еще каком-то открытом софте Моревну делают. интересно, надо бы глянуть, хотя есть ощущение, что там не совсем для геймдева. спасибо за наводку, попробую
Ну я и не в геймдеве я картинки оживляю, мне лишь бы двигать приятно было=)
эх. есть мечты когда-то хотя бы мини-мульт сделать, но ощущение, что в 3д это быстрее выйдет. как-то сценки делал для ролика про nintendo64, в ue4 в реалтайме получать качественную картинку было круто. хотя и 2д интересно, но даже представить тяжело, сколько там сил уходит.
spine дорогой, под 2 тыс баксов
Это для компаний.
Для простых пользователей все гораздо веселее.
Вопрос только в том, дает ли что-то Spine Pro, в сравнении с тем же DB?
То есть, я правильно понимаю, что DB может все то, что может Spine Professional?
Или все таки в чем-то уступает?
как бы банально это не звучало, но «есть свои плюсы и минусы». ненавижу эту фразу, но это так. то есть «теоретически» в db можно сделать все, что и в spine, то есть анимировать, меши, редактировать веса, итд. но тут как раз включаются миллион частностей и я уверен, что из-за специфики своей работы знаю далеко не все. но попробую.
Анимации для игры, грабли, шишки, костыли — Unity 3D, Anima 2D, Dragon bones, Spine
Материал посвящен тем кто разрабатывает игры, хочет начать это делать, начинающим аниматорам, художникам и всем кто работает с Unity 3d.
Я приветствую объективную критику, я пришел сюда не учить, а учиться и буду рад подсказкам и советам от более опытных людей.
Начало работы с Unity
Итак, ты придумал игру, идею и упаковал ее адекватно(99% начинающих этого не делают), разработал игровые механики, формулы, задатки сюжета, разработал увлекательный геймплей, что дальше?
В 3D для анимации есть только скелет, который оживляется руками или с помощью технологии захвата движений, кто это делал прекрасно понимает одно — это колоссальный труд, требующий десятки/сотни человеко-часов, для отличного результата.
В 2D у нас есть чертов выбор… между спрайтовой анимацией и скелетной анимацией, это принципиально разные способы организации и построения рабочих процессов.
В случае спрайтовой анимации — покадровая отрисовка кадров для последующего оживления в движке. Невероятный труд, тысячи кадров анимации, создание рефа (лучше 3D модели) облегчает отрисовку, но быстрее это не становится.
Для скелетной 2D анимации “как бы” есть выбор между Spine и Dragon Bones и
(не удивляйтесь) Anima 2D. Скажу сразу, выбора нет и он очевиден, для создания скелетной 2D анимации я рекомендую Spine.
Допустим мы не хотим тратить деньги на Spine, что же выбрать?
Зависит от требуемого результата. Anima 2D использует средства юнити для работы с ключевыми кадрами и кривыми и очень удобно когда анимация делается в движке и лежит сразу готовая, не надо экспорта/импорта, сборок, которые часто отталкивают начинающих разработчиков.
Но есть одно но, для меня это существенно, в Anima 2D нет деформации меша, да есть деформация меша от положения кости, но я не могу управлять мешем напрямую, для создания плавности анимации. Если очень постараться то результат будет впечатляющим, но мы не сможем переключить спрайт, такая функция отсутствует.
Dragon bones, китайская программа для скелетной анимации с потрясающими возможностями, выросла из плагина для флеш, есть возможность экспорта в Json файлы и формат Spine, возможность вывода PNG секвенции из анимации. Также удобное построение иерархии, переключение спрайтов, простота освоения.
Китайский спайн для бедных, используйте, но есть 3 проблемы:
Мой путь был именно таким — спрайтовая анимация>anima 2d>Dragon Bones>Spine
Оптимизация огромных атласов — отдельная история и когда нибудь я ее расскажу, про частицы и лвл дизайн тоже, я набрался шишек и готов бодать ворота.
Я могу долго рассказывать о кривых движения, плавности анимации, диснеевских принципах, общей динамике, весе и прочем. Но самое главное что я понял, вложи 300$ в свое будущее, это окупится с первого проекта на фрилансе. Не можешь и страшно? Привет 龙骨头(кости дракона).
DragonBones Getting Started Guide
Peter Huang (@fans8)
the DragonBones team (@dragonbonesteam)
DragonBones Getting Started Guide is released under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 unported license.
Table of Contents
What is DragonBones?
DragonBones is an open source project for 2D skeletal animation. It has a skeletal animation design panel named «DragonBonesDesignPanel» and a 2D skeletal animation library based on ActionScript.
Since the Design Panel is essentially an extension for Flash Pro, it makes possible for designers to build 2D skeletal animation based on the timeline workflow that designers are familar with, and build it with efficiency
Features
The animation is based on traditional timeline animation workflow.
Binding bones improves the quality of the animation and make it more accurate and natural. All bones can be controlled by the program dynamically.
Setting the scale and the delay of the animation time for a single bone is possible. This means a living and complex animation can be accomplished with less key frames.
The whole animation is made up of several pieces and each piece has its own tween effect. This structure will have much less bitmap and memory consumption comparing to «sprite sheets, sequence frames based» animation approach.
The view part and the logic part of the skeletal animation are separate. And the view part of the skeletal animation can be changed dynamically without any impact on the animation playback.
Animation by the project can be easily used in traditional DisplayList, the Starling framework and other technologies for 2D applications.
Download and installation setup
Get the Adobe Flash Pro 5.5 or above version from here
In following tutorial, we will guide you how to design and implement the animation.
Download the source code of tutorials
Next we will introduce how to use DragonBones with several simple examples.
Please download the related source code from here.
Tutorial 1: For designers Use DragonBones to create skeletal animation in Flash Pro
After download and install the design panel, start the Flash Pro and open the «DragonBones_tutorial_Start.fla» file in source code package.
Open the library panel in Flash Pro and you can see the related symbols for this example.
The «parts» folder contains all the elements that the animation «Dragon» is made up of. You can guess which part of the dragon it is by reading the name of each element. Naming a element clearly is a good practice, isn’t it? 🙂
Double click the MovieClip «Dragon» in the library panel to enter the edit mode. We need to understand how this animation is structured, which can help edit the skeletal animation later.
Pay attention to the name of each layer in the timeline because we name them as the related part of the skeleton. The design panel of DragonBones will recognize all the parts of the skeleton automatically according to the name of layers.
You should also note the layer named «label», where we add the label «walk» to indicate the motion of current timeline. If there are more than one motions, you will need to add more labels in corresponding position of the start frame. Label layer should be always on the top. This is very important! The design panel will read and set motions by these labels.
You may ask why there isn’t any tween in the timeline? Yes, all you need to do is to set key frames on the timeline and the rest of the work will be accomplished by the design panel.
As a designer, you may have added the tween in your animation, no worry, the design panel can import the animation as what it is designed. (The current version of DragonBones only supports classictween. New kinds of tween will be supported in later version)
After getting all of the requirements above ready, you can click Window>Other Panels>SkeletonAnimationDesignPanel in the Flash Pro menu to open the design panel. We will explain the details about the usage of design panel in following steps.
Click the «import» button in this panel, then you will see the following pop up window:
After importing the MovieClip «Dragon» to the design panel you will see the updated UI like following:
Armature List: List of imported movieClip. Each element in this list has the same name with the corresponding MovieClip in library and the program will use this name to create the animated object. Each MovieClip containing motions is called «Armature» in DragonBones.
Behavior List: Motion/Behavior names of corresponding animated objects. The name are got from the label name in the MovieClip and will be used by programs to play motions.
Bone Tree: The skeleton structure of animated objects. The name of each item is same with the name of related layer in the MovieClip.
Texture List: The texture name that is associated with each bone.
For each motion, you can also set the preferences like this:
Total Times: Duration of the selected motion. The larger the number is, the slower the motion goes.
Blending Times: Number of tween frames needed to switch from one motion to another. For example, there is a motion called «going down» which has only 1 frame in timeline, but if you set this parameter into 6, then the program will add addtion 6 frames long tween to make the switch more natural when there is a switch from one motion to the «going down» motion.
Keyframe Ease: The ease value between key frames within a motion.
Loop: Decide if the current motion should be played repeatly. Such as the «walk», «run» motions of a character.
After setting the parameters above, you can see the updated animation in the preview window which is in the bottom left of the design panel.
The button located at the bottom left corner of the preview window can scale the object to view it conveniently.
At the top right of the panel you can set the highlight color of the selected bone in the preview window.
In the list we can attach one bone as a child to the other bone by dragging it. As you see below, we set the body as the major bone and the head, tail, upper limb and lower limb as the children of major bone. The upper limb contains upper arm and lower arm as its children at the same time. By the tree structure we can see directly the subordination relation between bones.
We can set the motion parameters for each bone individually. Just select the bone you want to modify in the «BoneTree» panel and set these parameters:
Total Frames Scale: Set the scale of the total frames of current bone relative to the total frames of the motion
Be careful for these two parameters. After fine tuning of these two parameters, you will find that even there are only 2 key frames in the timeline, the motion of the character can be very complicated.
After adjusting the skeletal animation well, you can click the button «export».
There are many kinds of file format for export to meet your project requirement at the pop up list of «Export».
Zip(XML and SWF): Export the XML file and SWF file packed into a Zip file to store the skeletal animation and the visual resource individually.
Zip(XML and PNG): Export the XML file and PNG file packed into a Zip file to store the skeletal animation and the visual resource individually.
Zip(XML and PNGs): Export the XML file and PNG files packed into a Zip file to store the skeletal animation and the visual resource individually. There would be an individual PNG file for each bone.
In this example, we choose «PNG (XML Merged)» and click «OK» to export the file «DragonWalk.png» into a selected directory.
Notice that there is only a single PNG file get exported? Yes. Because we choose the export form that combines both XML data and skeletal data, so this PNG file contains all the data needed by the skeletal animation.
In Export Scale dropdown box, you can set the scale of exported texture atlas to provide assets with different dimension for devices with different resolution.
Tutorial 2: For programmers Use skeletal animation in ActionScript project
After designers export related assets and data into a predefined format file such as PNG or SWF, developers can use the skeleton animation library to import the file to program and control the characters to play. It is a very easy task with only a few steps! Following you will start to study how to use the skeletal animation library to render characters with traditional flash DisplayList or GPU base starling framework.
Download the Skeleton Animation Library, and import this project into your project. Let’s understand some basic concepts about skeletal animation before coding.
Factory: This is the basis for building skeletal animation. It is responsible for parsing the data from the imported file and preparing resources to create skeleton container, which is Armature.
Armature: We can consider it as a container which corresponds with a MovieClip exported from design panel in Flash Pro. Armature is responsible for skeleton management and playing animation.
Now let’s check out an example about how to create characters with traditional Flash DisplayList using skeleton animation library. Open the source code DB_Tutorial_Walk_DisplayList.as.
Firstly, import assets into your project.
This asset is exported from Flash Pro skeleton animation design panel, merged with png data and XML data. Of course you can also dynamic import it after application launched.
Create factory and parse resource data from function «fromRawData», then do other things in callback function «textureCompleteHandler».
In textureCompleteHandler, you need to create Armature with function «buildArmature»:
Add «armature.display» to stage.
Add armature to WorldClork for animation update:
Then, play some movement:
At last, call «WorldClock.clock.advanceTime(-1)» at ENTER_FRAME event handler.
Just the few lines of code, you can use skeleton animation in your own project. It is very cool, isn’t?
Next we talk about how to create the skeleton animation in Starling. Starling is a famous 2D open-source framework powered by Stage3D which can help you build high quality games. For more information about Starling, please visit its official web site: http://starlingframework.org.
Some users probably have been familiar with the way of creating animations in Starling: using the Sprite Sheet. However, it is a serious problem of memory consumption, especially when processing complex animations. Look at the picture below, it’s just a simple movement of walking, but takes up a big texture.
DragonBones have solved this problem. It can implement richer animation by using fewer assets (or textures).
DragonBones can work seamlessly with Starling, creating 2D skeleton animation which can be accelerated by GPU.
Open the DBStarlingWalk.as in the example project, you will notice that we create a special factory for Starling, the code like this:
And the rest of the codes, they are the same with the previous DisplayList example.
For Starling framework, the embedded skeleton animation assets can be PNG format ( which include the xml data) or the SWF format( which also include the xml data). SWF assets store data as vector graph, and then Skeleton Animation Library will transform them to bitmap textures at runtime. This can help you reduce the size of your project.
Tutorial 3: Create and control multiple Skeleton animations
Next, you will learn how to use DragonBones to create skeleton animation including multiple movements, and control these actions by keyboard interaction.
Open file DragonBones_Tutorial_MultiBehavior.fla, then double click the Dragon Element in library, you can see four motions: stand, walk, jump and fail. Frame labels have been added in start frame of each motion, which is way for DragonBones design panel to distinguish different motion.
Open Skeleton animation design panel, there are multiple motions listed in Behavior List. You can set total frame, tween and detail parameter for single bone by choose one motion.
Please pay attention to the Blending Times option in Behavior editor window.
This option is the duration of transition movement from other motion to current one. E.g. we set Blending Times of jump movement is 0.13, then 0.13 seconds will be needed from other motion to this jump motion.
DragonBones will automatically add frames to make the transition smoothly. Also you can preview the transition effects in the preview panels.
Click «Export» button to export Skeleton animation data after you finished the adjustment of each movement.
Open file DBStarlingMultiBehavior.as, the code following demenstrate how to use keyboard to control Skeleton animation in Starling.
You can find that whenever you want to play the Skeleton animation, just call function armature.animation.gotoAndPlay()
Not only the motion name, but also the total frame number and loop also can be specified dynamically by call this function.
DragonBones provide various events for each animation:
Movement change event:
Movement start event:
Movement complete event
Movement loop complete event:
You can easily create games including complex roles by various events and movement.
Tutorial 4: Control each bone in the skeleton annimation
For an interesting game, perhaps it is not enough to just play the predefined skeleton animations, for example we want the characters to have their own dynamic and controllable movements. To our great joy, DragonBones provides the mechanism to access and control each bone of the skeleton, which can make the characters free to do all kinds of motions.
In this example, the skeleton is controlled by the mouse movement in the scene. We create a bird that will follow the mouse movement and maintain a certain distance with the dragon. At the same time, the dragon’s head and arms will follow the bird movement and make a variety of poses. It sounds funny, right?
Let’s open the file DBStarlingControlBone.as and below is the corresponding code:
From the above code, we can find that method dragonBones.Armature.getBone(_name:String):Bone is used to get one specific bone. The node object of the bone contains the data, such as position, rotation, scale, skew and etc. We can assign values to these parameters based on the game logic needs, to achieve the effect of dynamic bone controlling.
Please pay attention to the updateBones() method in the above example, where we first fetch the angle between the mouse’s current position and the central point of the skeleton, then change the rotations of the dragon’s head and arms based on this angle, thus realize this interesting effect.
Tutorial 5: Switching texture in skeleton animation
It is very a common request in the game to switch texture for some effects like changing clothes, equipments or weapons for a certain characters, and this is very easy to get done by switching the corresponding bone texture in the DragonBones Animation library.
Through the mechanism of switching the bone texture, we can create new texture and bind it with the corresponding bones dynamically. The new texture can be obtained from external files that are created by other means, or from Texture Atlas that is exported from the design panel. You may have one question for now, how Flash Pro can export the texture that does not included in the timeline animation texture?
Open the sample file DragonBones_Tutorial_ChangeClothes.fla in this tutorial, and you will see the lovely dragon wear a yellow jacket with various actions that are designed on the layer called clothes.
Double click clothTextureTemp element, you will find that there have 4 clothes on the different layers with its associated names, and due to the identical size and shape, they overlap each other. However, in the actual project, the clothes or weapons may have various size, so it is necessary to set the appropriate relative coordination to its original texture.
Please note that the first frame label is named as «temp». The design panel won’t import animation element that do not have frame label.
Let’s get a close look at how to switch texture in the code. Open DBStarlingMultiBehavior.as file that is created in Tutorial 3, we can add switch texture code here directly. First, rename the imported texture to DragonWithClothes.png:
Please note that it is «parts/clothes1», not «clothes1». This is because that Flash Pro can have same element name under different folder, so DragonBones saved the path info which contains the directory. You will understand it when you see the directory that has clothes element in the library when you open DragonBones_Tutorial_ChangeClothes.fla
Create handler function that responses the key event (press C key), which is used to change texture.
Create changeClothes() function:
When you get familiar with DragonBones library, you can have more flexible implementation. For example, in addition to change bones’texture, you can also add, delete, update skeleton structure in Armature dynamically.
OK, you should know how to dynamically change the texture for your game’s characters, try it now! 🙂



































