Как запустить timeline через скрипт unity

от admin

Как запустить timeline через скрипт unity

Unity’s editor scripting is part of what makes the engine so attractive. Writing tools that directly interact with the rest of your game code is powerful and can make a large difference in the productivity of teams of all sizes. It also leads to a healthy landscape of third party integrations. In this post I will describe how two new Unity APIs allowed us to create a well integrated Unity toolkit for AnimVR and go through issues you might run into. Below is a video showcasing our integration:

A little Background

We have been working on the VR drawing and animation tool AnimVR for about a year. We are building it in Unity for a variety of reasons that I don’t want to get into now, but one of our main goals is to support import and export from and to a variety of interchange formats. So far the main way to export content from AnimVR is to use the Alembic Cache format which is very popular in feature film pipelines but barely used in the game industry.

We’ve also been teasing a Unity toolkit for ages. A prototype existed when we released the first beta version and at the time we thought it wouldn’t take us long to release it to the public. Unfortunately it turned out that back then we would have needed to include a lot of custom runtime code to make playback of AnimVR stages work in Unity. Getting any kind of consistent timing outside of playmode is cumbersome as most who’ve worked with Unity editor code will know. Additionally this would have been code we would have had to maintain and update alongside the main AnimVR application, slowing us down in a phase where we wanted to be able to react to feedback quickly.

A second concern of mine was that I believe third party importers should adapt to the concepts of the target application (Unity, in this case) rather than the source (AnimVR). This way imported assets can be used in all the ways natively supported assets can be. I want to enable people to build Unity projects where the content happens to be made in AnimVR, rather than “view” AnimVR projects in Unity.

We decided to not release that version of the Unity toolkit and wait until we had a better idea on how to reach that goal. So, what made it possible for us to release the current toolkit?

ScriptedImporters

Previously the only thing we had to work with regarding asset import were AssetPostprocessors, but those have major drawbacks that prevent a tight integration. With an AssetPostprocessor you can run code whenever Unity detects a file with a certain extension. This allows you to create new assets based on your custom files. Unfortunately there is no way to associate those newly created assets with the source file, meaning that you double the number of assets you have to manage. As far as Unity was concerned .stage files from AnimVR where random binary files with nothing meaningful in them. It also leads to worse UX, since there is a difference in how you work with natively support file types (like meshes, textures and audio) and custom file types.

Since Unity 2017.1 there is a way to handle all of that better and actually build importers that have the same UX as the native ones. Creating a custom ScriptedImporter allows you to associate assets with a file on disk. Whenever the file is updated the old assets are automatically discarded and recreated and deleting the file also deletes all associated assets. You can even add a custom editor for your file type that allows users to edit import settings in a familiar way. This makes support for custom files a lot cleaner.

The whole API is working well, but still marked as experimental. I’ll describe a few pitfalls that you need to watch out for in the implementation section of this post.

The inspector of our ScriptedImporter

The Timeline API

For a while now Unity has been trying to break into the “realtime cinematics” market. The central building block of those efforts is the Unity Timeline API that was added in Unity 2017.1 and is still actively being developed. It provides a way to lay out tracks and clips in time and play them back, in a way that should be familiar to anyone who’s used video or sound editing software. It’s also very extensible, allowing you to define custom “Playables” that get updated whenever the playback time changes.

This maps very nicely to our AnimVR stages. They consist of a number of layers (e.g. paint, mesh, audio, camera, etc.) that are laid out in time. Initially we actually considered using the Timeline API at runtime in AnimVR, but after some experimentation we concluded that our use case didn’t need many of the features that the API provides and that this would uneccesarily complicate our daily work. Now we’re using Timeline to drive the animation in the imported assets. It allows us to make use of a rich API without complicating our runtime code and lets users use AnimVR stages as part of their exisiting timeline setup.

The resulting Unity Timeline

Implementation

Loading the Data from Disk

When an asset with the right extension is imported Unity calls OnImportAsset(AssetImportContext ctx) on your ScriptedImporter . The AssetImportContext contains all the necessary information to find the relevant file on disk and read it. In our case we use the same deserialization method as in standalone AnimVR which should make it easy to keep compatibility between the Unity toolkit and the main application.

Creating Assets from Script

While working with the Timeline API you will notice that it is fairly unintuitive to use from code. This is partly due to the fact that there is little documentation and few “real world” examples and partly because many settings are private variables that only get exposed in the UI. So far I’ve managed to keep afloat by decompiling the Timeline related code that comes with Unity and then using reflection to access the variables I need, which is par of the course for any Unity editor scripting.

A PlayableDirector

Any object that wants to play back a Timeline needs a PlayableDirector component. The PlayableDirector provides the adapter between the TimelineAsset that can’t reference any objects in the scene and the scene objects that are controlled with the Timeline. It’s a regular component and you can simply created it like this:

The Timeline

Creating the timeline asset itself is very straightforward. Just remember to use CreateInstance like with any other ScriptableObject . Here is how we do it in the toolkit:

Note the call to ctx.AddSubAsset . This is essential, because by default any assets that are created during the import process are destroyed automatically by Unity. Only assets that are registered via ctx.AddSubAsset will be kept. If you forget this for an asset it’ll most likely manifest in missing references. What needs to be added is usually fairly clear, but there are some tricky cases that I’ll discuss later.

Quick Tip: The “name” of the sub asset needs to be unique and the same across imports. I use AnimationUtility.CalculateTransformPath to quickly create legible, and likely unique names for assets associated with an imported sub object.

Tracks

In its default state the TimelineAsset doesn’t have any tracks. You can add a new track to the Timeline as follows (in this case it’s an “Activation Track”).

As pointed out in the code, any tracks you add to a TimelineAsset need to be saved as sub assets too. If you don’t do that the tracks will be missing after the import is done and you won’t even get an error message!

Clips

Now, adding a clip to a track is easy:

Again, you need to watch out to save the right asset. In this case it turns out that the clip itself is actually stored as part of the track, so you don’t need to do anything there. Still, every clip has an associated IPlayableAsset which needs to be saved seperately and can be accessed via TimelineClip.asset .

Quick Tip: With clips you get to think about three “names”. clip.asset.name is the name of the UnityEngine.Object and the string shown when you look at the asset in the editor, clip.displayName is what is shown in the Timeline window on the clip and finally you need to pass a unique identifier to AddSubAsset (the other two can be chosen freely).

TimelineClip.asset is not type safe, you need to cast it to the correct asset type which is not clearly indicated. What I usually do is to jump to the definition of the associated track and check its attributes.

The TrackClipType attribute tells you what the type of TimelineClip.asset will be when you create the clip with CreateDefaultClip() .

Referencing Prefabs

If the tracks and clips you are creating are self contained you are done now. Unfortunately that’s usually not the case, because in the end you want to control objects and scripts via your timeline. This is also the case with our ActivationTrack . If you create that type of track in the editor you’ll see something like this:

ActivationTrack in the Timeline window.

The field on the left lets you drag in the GameObject you want to control via that track. But how do you assign that value from script? Unfortunately there is no public controlledObject field in the ActivationTrack class or anything similar. This is because you are supposed to be able to use the same TimelineAsset with different PlayabaleDirectors . Hence there needs to be a way for us to define “references” in the TimelineAsset and then use the PlayableDirector to fill them. And there are two (of course) very different ways to do that!

ExposedReferences

The first way is to use a member variable of type ExposedReference<ReferencedType> and it’s used in the default ControlTrack . Each ExposedReference instance needs to have a unique value for exposedName . On the PlayableDirector you can then call SetReferenceValue with the name of the ExposedReference you want to assign and the value it’s supposed to have.

Unfortunately, as far as my testing goes, the mapping set via SetReferenceValue is not updated correctly when instatiating prefabs. Usually, when you reference GameObjects in a prefab and the prefab is instantiated, those references are updated to point to the corresponding instantiated objects. This is not the case with ExposedReference values. When you instatiating your imported object the references will still point to the prefabs instead to objects in the scene.

Generic Bindings

The other way to reference objects seems a lot more powerful, but is also barely documented. This section is speculation based on what I was able to figure out in my experiments.

The way ActivationTracks decides which GameObject to control is done via PlayableDirector.GetGenericBinding . The Set/GetGenericBinding methods allow you to map an asset (e.g. a TimelineTrack ) to any object (including GameObjects ) and retrieve that mapping later. So, when we create the ActivationTrack we do the following:

The track will then later use this binding by calling director.GetGenericBinding(this); . The interesting points here are that

  1. Generic Bindings are serialized with the PlayableDirector .
  2. When instantiating a prefab with a PlayableDirector attached all the references will be automatically updated the corresponding instantiated objects.

This is exactly what we want! With the last step complete, we can now create a fully functional Unity Timeline in a ScriptedImporter.

Conclusion

ScriptedImporters are a very powerful new feature in Unity and let you import complex custom files. The new Timeline API is great if you need to lay out things in time, but can be tricky to work with from code unless you know exactly what’s going on. There are a few things you need to do to make ScriptedImporters work with the Unity Timeline API.

  • Remember to call AddSubAsset on the right things.
    • The TimelineAsset
    • Any TrackAsset you create
    • The TimelineClip.asset of any clip you create

    I left out the whole inspector/import settings side of things since that should be fairly straight forward for anyone familiar with regular Unity editor coding, but I’m happy to answer questions regarding that as well.

    Dario Seyb
    PhD Student

    I am a software engineer interested in computer graphics, physically based rendering and real time graphics.

    Знакомство с Timeline в Unity

    Чтобы рассказать часть сюжета игры или увлечь игрока, разработчики часто используют катсцены. В некоторых играх создают специально отрендеренные анимированные сцены с моделями высокой детализации, в других же применяют настоящие внутриигровые модели. Благодаря использованию внутриигровых моделей можно сэкономить много средств и времени, потому что вам не придётся создавать новые модели, риги и анимации исключительно для катсцен. Но даже если вы используете уже готовые модели, то это не означает, что нужно жертвовать спецэффектами или драматизмом! В Unity есть мощный инструмент, позволяющий создавать захватывающие катсцены — Unity Timeline!

    В этом туториале вы познакомитесь с Timeline и узнаете, как создавать катсцены с анимациями и сменами камер.

    Приступаем к работе

    Скачайте проект-заготовку и готовый проект отсюда.

    Откройте файл Starter Project и загрузите сцену Main. Она будет нашим фундаментом. В ней есть герой, стоящий на башне и глядящий на мир:

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

    Что же такое Timeline?

    В этом туториале мы будем работать с Unity Timeline — но что такое timeline? Timeline — это GameObject с компонентом timeline, который можно редактировать в окне Unity Timeline, управляющем ключевыми кадрами анимации и циклами жизни объектов. При создании катсцены с помощью Unity Timeline, мы задаём ключи анимации и определяем, когда они должны сработать. В этом туториале мы также будем использовать AnimationController, который можно воспринимать как надмножество ключевых кадров анимации.

    Когда персонаж выполняет анимацию, например, ходьбы, каждой отдельной подвижной вершине объекта необходимо указать её путь. В этом туториале мы не будем заниматься созданием модели и риггингом анимаций — всё уже сделано за нас. Но полезно будет знать, что когда вы вручную задаёте ключевой кадр анимации или используете анимацию AnimationController, то по сути они являются одним и тем же: позицией объектов в заданный момент времени. Timeline управляет всеми этими движениями для создания сцены. Всё это вы поймёте, когда начнёте разбираться в Unity Timeline.

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

    1. Timeline Asset: это дорожка, привязанная к находящемуся в иерархии GameObject. В ней хранятся связанные с этим GameObject ключевые кадры, используемые для выполнения анимаций или для определения того, активен ли GameObject.
    2. Associated GameObject: это GameObject, с которым связана дорожка.
    3. Frame: это текущий заданный кадр Timeline. Когда нам нужно изменить анимации, мы задаём ключевые кадры в начальном и конечном кадрах.
    4. Track Group: при увеличении масштабов сцены увеличивается и количество дорожек. Можно упорядочивать дорожки, группируя их.
    5. Record Button: когда эта кнопка активна, мы можем менять текущий кадр и задавать позицию и/или поворот GameObject в сцене. При этом изменения будут записаны.
    6. Curves Icon: при нажатии на этот значок откроется окно Curves, в котором можно точнее настроить подробности связанных ключевых кадров анимации, чтобы изменить их нужным способом.

    Свет, камера, МОТОР!

    Загрузив основную сцену, нажмите Play. Вы должны увидеть героя, стоящего на вершине башни:

    Это анимация по умолчанию, заданная в Animation controller. В этом туториале мы будем использовать заранее созданные анимации, поэтому вам не нужно беспокоиться о внутреннем устройстве моделей, анимаций или контроллеров. Но если вы хотите разобраться в этом процессе, то можете изучить наш туториал Introduction to Unity Animation.

    Создание GameObject типа Timeline

    Первым шагом будет создание GameObject Timeline. Создайте пустой GameObject, нажав правой клавишей мыши (на Mac — с зажатым Command) на окне Hierarchy и выбрав Create Empty. Так мы добавим в сцену GameObject и выберем его:

    Не снимая выделения с GameObject, откройте меню Window и выберите Timeline. Откроется окно Timeline. Нажмите на кнопку Create, откроется диалоговое окно Save. Измените название файла на Timeline и нажмите на Save:

    Переименуйте GameObject в Timeline, щёлкнув по нему, нажав клавишу F2 и введя Timeline:

    Мы создали GameObject Timeline, который будет координировать все анимации и смены камеры в катсцене. Внутри движка Unity сохранил на диск файл ассета под названием Timeline.playable. В GameObject Timeline Unity добавил компоненты Playable Director и Animator.

    Компонент Playable Director содержит поле Playable, привязанное к только что сохранённому нами ассету Timeline. Добавленный Unity компонент Animator в теории должен позволить нам анимировать GameObject Timeline, но мы этого делать не будем, так что можно просто её проигнорировать.

    Прежде чем двигаться дальше, я хочу перетащить вкладку Timeline в нижнюю часть экрана. Это позволит нам одновременно открыть окна Scene и Timeline:

    Выберите GameObject Timeline и вернитесь в окно Timeline. На данный момент нам есть дорожка Animation Track для GameObject Timeline. Она нам не понадобится, поэтому можно выбрать её и нажать Delete, чтобы удалить:

    Анимируем прыжок!

    Теперь мы готовы приступить к анимациям. Разверните GameObject Hero, чтобы увидеть GameObject Model. Выберите GameObject Timeline. Перетащите GameObject Model в окно Timeline; при этом откроется меню дорожки, поэтому выберите Animation Track. Повторите этот шаг для GameObject Hero:

    Записываем ключевые кадры

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

    Выберите в окне Timeline дорожку Hero и нажмите на кнопку Record (красный круг), чтобы начать запись. Выберите GameObject Hero в окне Hierarchy и задайте его X Position равной -1, а затем сразу же присвойте его X Position значение 0.

    Вернитесь в окно Timeline и нажмите кнопку Record на дорожке Hero, чтобы завершить запись. Так мы добавили ключевой кадр для начальной позиции героя:

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

    Проще всего это сделать, присвоив X Position объекта значение -1 относительно его текущей позиции, а затем вернуть значение на место. В этом туториале мы несколько раз воспользуемся таким трюком.

    Далее нам нужно, чтобы герой подождал 100 кадров, прежде чем спрыгнет с башни. В настоящий момент мы задали только начальную позицию героя, но нам нужно задать герою ту же самую позицию (т.е. на вершине башни) через 100 кадров. В противном случае Unity сразу же начнёт интерполировать движение.

    Как и раньше, выберите GameObject Timeline, однако на этот раз нужно нажать на поле кадров вверху окна и ввести «100». Так мы переместим ключевой кадр в кадр 100.

    Нажмите кнопку Record дорожки Hero. Выберите GameObject Hero и в поле Transform окна Inspector присвойте его X Position значение -1, а затем сразу же верните обратно к 0. Нажмите кнопку Record ещё раз, чтобы остановить запись.

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

    Добавляем анимационные клипы

    Задание данных позиции

    Сначала нам нужно задать данные позиции.

    Нажмите на GameObject Timeline, чтобы выбрать его. В окне Timeline добавьте к дорожке Model анимацию Animation, нажав правой клавишей мыши (на Mac — щёлкнув с зажатым Command) на дорожку Model и выбрав Add From Animation Clip. Теперь выберите анимацию Idle:

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

    Для этого сначала выберите окно Timeline, а затем перейдите к кадру 138. Нажмите в дорожке Hero кнопку Record. Теперь выберите GameObject Hero. В поле Transform окна Inspector, задайте Y Position значение 3.934, а Z Position — значение 1.97.

    Вернитесь в окно Timeline и перейдите к кадру 176. Снова выберите GameObject Hero и задайте Y Position значение 0, а Z Position значение 5.159. Завершите запись, нажав на кнопку Record:

    Сохраните сцену и нажмите Play, чтобы увидеть результат своей работы!

    Мы задали данные позиции, но не выполняемые с ними анимации. Сейчас мы займёмся этим.

    Выбрав окно Timeline, нажмите правой клавишей мыши (на Mac щёлкните с зажатым Command) на дорожке Model и щёлкните на Add From Animation Clip, а затем выберите Jump. Так вы добавите анимацию Jump сразу после анимации Idle.

    Перетащите правую сторону анимации Jump, чтобы она находилась в кадре 176. Теперь мы добавим ещё один Animation Clip, но на этот раз мы будем добавлять анимацию Land (её длину изменять не нужно, просто добавьте её):

    Сохраните сцену, нажмите Play и посмотрите на результат!

    Добавляем камеры

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

    В окне Hierarchy переименуйте MainCamera в Camera1. Выберите GameObject Timeline. Перетащите Camera1 в окно Timeline, при этом откроется меню выбора дорожки; выберите Activation Track. Перетащите полосу Active дорожки Camera1 так, чтобы она заканчивалась на кадре 157:

    Активностью или неактивностью GameObject во время сцены управляет Activation Track. Наша основная камера теперь отключится после кадра 157. Нажмите Play и посмотрите на результат:

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

    В окне Hierarchy выберите Camera1 и создайте её дубликат, нажав Control-D (Command-D на Mac). Переименуйте дубликат в Camera2 и отключите его.

    В этом туториале мы используем ещё две камеры, поэтому создадим их сейчас, повторив тот же алгоритм; переименуйте их в Camera3 и Camera4 и отключите. После этого все игровые объекты Camera, кроме Camera1, должны оказаться отключенными. Вот, как должна выглядеть иерархия:

    Теперь мы расположим Camera2. Выберите Camera2 и в поле Transform окна Inspector задайте Y Position значение 10.75, а Z Position значение 2.84. Параметру X Rotation задайте значение 79.5:

    Что касается Camera1, то выберите окно Timeline и перетащите в него из Hierarchy объект Camera2; при этом снова появится меню выбора дорожки, поэтому выберите Activation Track. Перетащите полосу Active так, чтобы она начиналась сразу после завершения активации Camera1 (кадр 158). Перетащите правую сторону дорожки Active для Camera2 так, чтобы она заканчивалась на кадре 216.

    Сохраните сцену, нажмите Play и понаблюдайте за сменой камер в вашей сцене.

    Настало время добраться до сокровища!

    Смотрим на сундук

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

    Выберите GameObject Timeline и установите кадр 202. Нажмите на кнопку Record в дорожке Hero, чтобы начать запись.

    Выберите GameObject Hero и в поле Transform окна Inspector задайте Y Rotation значение -1, а затем сразу же измените значение обратно на 0, чтобы задать начальный ключевой кадр поворота GameObject Hero.

    Закончив с этим, снова выберите GameObject Timeline и установите кадр 216. Снова выберите GameObject Hero и в поле Transform окна Inspector задайте Y Rotation значение -90.

    Кроме того, герой должен в этот момент находиться в состоянии ожидания, поэтому добавьте в дорожку Model Animation Track анимацию Idle и сделайте так, чтобы она длилась до кадра 216:

    Итак, наш герой приземлился и готов искать сокровище. Настало время направиться к нему и открыть сундук!

    Подсказка: если дорожка Timeline становится слишком большой, то можно покрутить колесо мыши, чтобы изменить его масштаб. Для перемещения влево или вправо, нажмите и удерживайте среднюю клавишу мыши, перемещая её влево или вправо.

    Приближаемся к сокровищу

    Выберите GameObject Timeline и установите кадр 216. Нажмите на кнопку Record на дорожке Hero, чтобы начать запись.

    Выберите GameObject Hero и в поле Transform окна Inspector задайте X Position значение -1, а затем снова вернитесь к 0, чтобы установить ключевой кадр начальной позиции. Далее на Timeline выберите на дорожке Hero кадр 361.

    Вернитесь к GameObject Hero и в поле Transform окна Inspector задайте X Position значение -6. Вернитесь к дорожке Hero и завершите запись.

    Наконец задайте объекту Model анимацию Walk, выполнив те же действия, что и раньше, а затем растяните его до кадра 361:

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

    Чтобы камера Camera2 не следила за всем путём героя, теперь мы можем использовать камеру Camera3 для съёмки из-за спины героя.

    Для этого в основном меню окна Hierarchy выберите и перетащите Camera3 на GameObject Model, который находится внутри GameObject Hero, чтобы сделать камеру его дочерним элементом.

    Задайте Camera3 позицию (X:0, Y:2.06, Z:-2.5). Задайте ей поворот (X:0, Y:0, Z:0). Иерархия должна выглядеть следующим образом:

    Благодаря тому, что Camera3 теперь является дочерним элементом GameObject Model, она будет повторять все движения GameObject Model, глядя на него сзади. Однако для Camera3 по-прежнему нужна дорожка активации, чтобы она активировалась в нужное время.

    Перетащите GameObject Camera3 на Timeline и выберите Activation Track, как мы делали это с Camera1 и Camera2. Задайте в качестве начального кадра Camera3 конечный кадр Camera2, а в качестве конечного кадра Camera3 задайте 361:

    Теперь сохраните сцену, нажмите Play и посмотрите, как всё получается:

    Мы уже почти всё сделали! Теперь герой просто должен открыть сундук… конечно же, пнув по нему!

    Открываем сундук

    Для последнего ракурса мы используем камеру Camera4, настроив её так, как мы это сделали с Camera1 и Camera2.

    Перетащите Camera4 в Timeline и добавьте Activation Track. Установите начальный кадр Camera4 в конец фазы активности Camera3 и растяните его до кадра 555. Это должно выглядеть так:

    Добавьте анимацию Kick. Нажмите правой клавишей мыши (на Mac щёлкните с зажатым Command) на дорожке Model. Выберите Add Animation From Clip, а затем выберите Kick. Не изменяйте длительность. Теперь дорожка Model должна выглядеть следующим образом:

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

    Разверните GameObject ChestBottom в окне Hierarchy. Перетащите GameObject ChestLid в Timeline и выберите Animation Track. В Timeline установите кадр 389. Теперь выберите дорожку ChestLid. Нажмите на кнопку Record.

    Теперь, когда запись выполняется, выберите GameObject ChestLid в окне Hierarchy window и задайте X Position значение -1, а затем вернитесь к 0, чтобы задать исходное положение. В окне Timeline установите кадр 555. Наконец, в поле Transform окна Inspector задайте Y Position ChestLid значение 6. Снова нажмите кнопку Record на дорожке, чтобы завершить запись.

    Так мы анимируем крышку сундука, чтобы она пролетела сквозь стену.

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

    Задайте объекту Camera4 позицию (X:-9.00, Y:5.4, Z:5.18). Задайте Camera4 поворот (X:90, Y:0, Z:0).

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

    Выберите окно Timeline. Перетащите в него GameObject Camera4 и создайте Animation Track. Установите для дорожки кадр 389. Нажмите на дорожку Camera4, а затем щёлкните кнопку Record. Выберите GameObject Camera4. В поле Transform окна Inspector задайте X Position значение 0, а затем снова -9.

    В окне Timeline перетащите Animation Track в кадр 555.

    Наконец задайте Y Position объекта Camera4 значение 3.74:

    Сцена наконец завершена. Нажмите на Play и оцените её!

    Управляемся со сложностью: группирование дорожек

    Это была короткая анимация всего с парой «актёров», поэтому нам было довольно легко отслеживать игровые объекты и дорожки. Но при создании более сложных сцен со множеством подвижных частей и актёров ими становится очень сложно управлять. Именно поэтому очень необходима упорядоченность. Хотя сцена уже готова, давайте потратим несколько минут на её упорядочивание — в будущем вы ещё поблагодарите себя за это.

    Один из способов упорядочивания работы — группирование дорожек. Сначала нажмите правой клавишей мыши под дорожками в окне Timeline и выберите Track Group. Нажмите на Track Group и в Inspector измените её имя на Activations:

    Повторите этот процесс и создайте Track Group под названием Animations. Теперь Timeline должна выглядеть так:

    Теперь перетащите все дорожки с разделами Active в группу Activations, а все остальные в группу Animations. Теперь вы сможете открывать и закрывать каждую группу для удобства работы с ними:

    Не забывайте сохранять свою работу. Откиньтесь на спинку своего режиссёрского кресла и похвалите себя — вы закончили свою первую Timeline.

    Куда двигаться дальше

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

    Мы хорошо потрудились и создали катсцену с использованием анимаций модели, сменой камер и обновлениями жизненных циклов объектов, однако здесь ещё многое можно изучить. Один из самых важных аспектов, связанных с Timeline — это создание собственных скриптов, в которых можно связать анимации с кодом, который можно выполнять вместе с ними. Подробнее о скриптах можно узнать здесь. Если вы уже хорошо освоились, то попробуйте добавить в сцену скрипт после открытия сундука с сокровищами.

    Если вам интересно больше узнать об анимациях в Unity в целом, то изучите наш замечательный туториал Introduction to Unity Animation.

    Чтобы узнать больше о создании 3D-моделей и об окне Animation, изучите подробную серию туториалов разработчиков Unity, представленную здесь.

    И последнее — если вас интересует создание игр, то можете приобрести нашу книгу Unity Games By Tutorial. В ней рассказывается о создании с нуля четырёх типов игр с подробным описанием каждого этапа процесса.

    TimelineClip.start

    Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

    Submission failed

    For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

    Description

    The start time of the clip.

    Did you find this page useful? Please give it a rating:

    Thanks for rating this page!

    What kind of problem would you like to report?

    Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at

    Thanks for letting us know! This page has been marked for review based on your feedback.

    If you have time, you can provide more information to help us fix the problem faster.

    You’ve told us this page needs code samples. If you’d like to help us further, you could provide a code sample, or tell us about what kind of code sample you’d like to see:

    You’ve told us there are code samples on this page which don’t work. If you know how to fix it, or have something better we could use instead, please let us know:

    You’ve told us there is information missing from this page. Please tell us more about what’s missing:

    You’ve told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:

    You’ve told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:

    You’ve told us there is a spelling or grammar error on this page. Please tell us what’s wrong:

    You’ve told us this page has a problem. Please tell us more about what’s wrong:

    Thanks for helping to make the Unity documentation better!

    Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.

    Copyright © 2018 Unity Technologies. Publication: 2018.2-002P. Built: 2019-01-17.

    How can I trigger to start timeline using distance and not OnTriggerEnter/Exit?

    The idea is to create some kind of cut scene. Once the player (First person, in the screenshot i’m just showing the door on the left where the player will come from and the soldiers ) exit the door on the left and is in a specific distance from the soldier the first soldier the closet one will start moving to the player. Later I will make that it will change to close up view on the soldier with some text conversion. That’s the main goal.

    But the script the original script by the unity tutorial is using triggers. I’m not sure if I should using this way or using somehow by calculating the distance between the player and the soldier to start the timeline ? And how to do it.

    Cut scene

    After the soldier is moving/walking to the player at some point I will make it to change to a close up view on the soldier with blurry background something like this:

    Читать:
    Define c что это

Related Posts