Что такое cinemachine в юнити

A Guide to Cinemachine

  1. Add a Cinemachine Brain component to the main camera.

Using Cinemachine

Transform Based Cinemachine

For example, we have this basic timeline setup of a player model moving towards a certain point.

  1. First, drag the “MainCamera” into the timeline and select “Add Cinemachine Track.” Then right-click the new Cinemachine Track and select “Add Cinemachine Shot.”
  2. Select the new Cinemachine Shot from the timeline, and in the inspector, look for the “Virtual Camera” property then click Create, this creates a new Virtual Camera for us to use.
  3. After creating a new virtual camera, assign the “Kart” game object to the “Look At” property of the “Cinemachine Virtual Camera” component.
  4. Set the virtual camera’s position and adjust the soft zone and dead zone to your liking. Also, don’t forget to adjust the Cinemachine Shot clip’s start and end on the timeline.
  5. This would be the final output:

Track and Dolly

  1. Create a new Dolley Camera with Track ( Cinemachine Tracked Dolly ).
  2. The created dolly track is a series of waypoints for the virtual camera to move between. To create a new waypoint, click on the plus button on the inspector.
  3. To create a path for the virtual camera, we can adjust the waypoints in the scene view that will automatically update the waypoint’s transform in the inspector.
  4. We can adjust the position of our camera along the path between waypoints by selecting our camera and adjusting the value of Path Position in the inspector. Each integer value represents the position of a waypoint on the track.

(Ex: 0 = 0 waypoint, 1 = 1 waypoint)

5. We can then record and animate the Path Position value by assigning the virtual camera to an animation track in the timeline.

As you can see, the camera follows the player whenever the player moves back and forth. But, when the player moved far away from the track, the camera stopped at the last waypoint.
— If you want to add another shot from another track and dolly camera, we can assign different virtual cameras to each clip in a new cinemachine track.

After adding new Cinemachine Shots, you then assign each of their respective cameras and adjust the duration and timing of each clip accordingly in the timeline.

State-Driven

  1. Create a new Cinemachine State-Driven Camera ( Cinemachine State-Driven ).
  2. The virtual camera children’s property in the inspector lists all the virtual cameras that our state-driven camera is going to use. You can add existing virtual cameras by assigning it as a child of the State Driven camera.
  3. After setting up the shots on each of our virtual cameras, we can now set up our states. Any animator component in our scene can trigger states. First, assign the animator on the Animated Target property.
  4. We can then add new States and assign them to their respective cameras.
    Note:
    — You can adjust the number of seconds to wait before entering a state by changing the value of Wait.
    — You can change the default blend setting from the list, or you can create a custom blend asset to customize the blend for different states.

Free Look

  1. Create a new Cinemachine Free Look Camera ( Cinemachine Free Look ).
  2. You can then assign the transform for the «Follow» and «Look at» property.
  3. In the scene view, you can see three circles generated around the player character. They represent the orbit for the three camera rigs (TopRig, MiddleRig, and BottomRig).

4. You can edit this through Axis Controls.

— Just like other virtual cameras, you can also change the lens settings of each rig.

— You can also enable to use of the Common Lens property, which applies the lens settings to all three child rigs. Otherwise, child rig settings will be applied.

Clear Shot

  1. Create a new Cinemachine ClearShot Camera ( Cinemachine ClearShot ).
  2. Cinemachine automatically adds a new virtual camera as a child of Cinemachine ClearShot camera. You can add existing virtual cameras by assigning it as a child of the ClearShot camera.
  3. On the parent, assign which object to track, by setting the transform of the «Look At» property.
  4. Check if the child camera has a Cinemachine Collider component. This helps in assessing the quality of shots.
  5. Set a value for the child’s Optimal Target Distance. If greater than zero, a higher score will be given to shots when the target is closer to this distance. You can experiment with this value to get optimal results.
  1. Import Post Processing V2 Adapter Asset Package.
  2. On your Main Camera, add a Post-process Layer component
    ( Cinemachine Post-Processing ).
  3. Set the layer of the Main Camera to a custom layer named PostProcessing.
  4. Also, set the Volume blending Layer to PostProcessing.
  5. You can create a default post-process globally on all virtual cameras by adding a post-process volume component on our main camera and enabling Is Global property.

First Camera:

Duplicate Camera:
* Changed the focus of the camera on a much closer range.

Note:
— When we are Tracking a target (Look At) and using a Depth of Field effect, we can enable the Focus Tracks Target that dynamically pulls focus on our target based on its distance from the camera.

(Without Post-Processing):

Cinemachine 2D

  1. Create a new Cinemachine 2D Camera ( Cinemachine Virtual Camera ).
  2. Assign the “Player” prefab to the “ Look At ” and “ Follow ” property.
  3. Adjust the Soft Zone and Dead Zone .
  4. Add a Cinemachine Confiner component.
  5. Create a “GameObject” with a “PolygonCollider 2D” component. Edit the collider and set it to your desired size and position. Also, don’t forget to set it to “IsTrigger.”
  6. Assign the created “GameObject” with “PolygonCollider2D” to the Virtual Camera’s Cinemachine Confine Component: “Bounding Shape 2D” property.
  7. This would be the final output.

You can notice that when the player leaves the dead zone and goes toward the soft zone, the camera starts tracking the player and moves in that direction.

Definitions

Cinemachine Brain

This is the central Cinemachine component that does all the magic. It’s a component attached to the Unity camera, and it monitors all the Virtual Cameras in the scene and drives the Unity camera using the shot it likes best.

What happens is that there is only one Unity Camera. The brain that gets installed on it is responsible for positioning and configuring that one camera to be in the right place at the right time, according to the instructions provided by the virtual cameras that the brain is observing.

Cinemachine Virtual Camera

This component is intended to be attached to an empty Transform GameObject, and it represents a Virtual Camera within the Unity scene.

The Virtual Camera will animate its Transform according to the rules contained in its CinemachineComponent pipeline (Aim, Body, and Noise). When the virtual camera is Live, the Unity camera will assume the position and orientation of the virtual camera.

A virtual camera is not a camera. Instead, it can be thought of as a camera controller, not unlike a cameraman. It can drive the Unity Camera and control its position, orientation, lens settings, and PostProcessing effects. Each Virtual Camera owns its own Cinemachine Component Pipeline, through which you provide the instructions for dynamically tracking specific game objects.

A virtual camera is very lightweight and does no rendering of its own. It merely tracks interesting GameObjects and positions itself accordingly. A typical game can have dozens of virtual cameras, each set up to follow a particular character or capture a particular event.

A Virtual Camera can be in any of three states:

  • Live : The virtual camera is actively controlling the Unity Camera. The virtual camera is tracking its targets and being updated every frame.
  • Standby : The virtual camera is tracking its targets and being updated every frame, but no Unity Camera is actively being controlled by it. Standby is the state of a virtual camera that is enabled in the scene, but at a lower priority than the Live virtual camera.
  • Disabled : The virtual camera is present but disabled in the scene. It is not actively tracking its targets, and so consumes no processing power. However, the virtual camera can be made live from the Timeline.

The Unity Camera can be driven by any virtual camera in the scene. The game logic can choose the virtual camera to make live by manipulating the virtual cameras’ enabled flags and their priorities, based on game logic.

To be driven by a virtual camera, the Unity Camera must have a CinemachineBrain behavior assigned to it. This behavior will select the most eligible virtual camera based on its priority or other criteria, and manages blending.

Look At

The object that the camera wants to look at (the Aim target). If this is null, then the vcam’s Transform orientation will define the camera’s orientation.

Follow

The object that the camera wants to move with (the Body target). If this is null, then the vcam’s Transform position will define the camera’s position.

Cinemachine Tracked Dolly

A Cinemachine Virtual Camera Body component that constrains camera motion to a CinemachinePath or a CinemachineSmoothPath. The camera can move along the path.

This component can operate in two modes: manual positioning and Auto-Dolly positioning. In Manual mode, the camera’s position is specified by animating the Path Position field. In Auto-Dolly mode, the Path Position field is animated automatically every frame by finding the position on the path that’s closest to the virtual camera’s Follow target.

Cinemachine State-Driven

This is a virtual camera «manager» that owns and manages a collection of child Virtual Cameras. These child vcams are mapped to individual states in an animation state machine, allowing you to associate specific vcams to specific animation states. When that state is active in the state machine, then the associated camera will be activated.

You can define custom blends and transitions between child cameras.

To use this behavior, you must have an animated target (i.e., an object animated with a state machine) to drive the behavior.

Cinemachine Free Look

A Cinemachine Camera geared towards a 3rd person camera experience. The camera orbits around its subject with three separate camera rigs defining rings around the target. Each rig has its radius, height offset, composer, and lens settings. Depending on the camera’s position along the spline connecting these three rigs, these settings are interpolated to give the final camera position and state.

Player input is supplied along two axes: the X-axis, which controls the orbital position (see CinemachineOrbitalTransposer), and the Y-axis, which controls the vertical position on the spline connecting the three child rigs.

Each child rig can have its Lens settings, or commonly shared values can be used. Additionally, each child rig can have its Composer and Noise settings.

Cinemachine Clear Shot

Cinemachine ClearShot is a «manager camera» that owns and manages a set of Virtual Camera gameObject children. When Live, the ClearShot will check the children, and choose the one with the best quality shot and make it Live.

This can be a very powerful tool. If the child cameras have CinemachineCollider extensions, they will analyze the scene for target obstructions, optimal target distance, and other items, and report their assessment of shot quality back to the ClearShot parent, who will then choose the best one. You can use this to set up complex multi-camera coverage of a scene and be assured that a clear shot of the target will always be available.

If multiple child cameras have the same shot quality, the one with the highest priority will be chosen.

You can also define custom blends between the ClearShot children.

Cinemachine Post-Processing

As a component on the Virtual Camera, it holds a Post-Processing Profile asset that will be applied to the camera whenever the Virtual camera is live. It also has the optional functionality of animating the Focus Distance and DepthOfField properties of the Camera State and applying them to the current Post-Processing profile.

Cinemachine Collider

An add-on module for Cinemachine Virtual Camera that post-processes the final position of the virtual camera. Based on the supplied settings, the Collider will attempt to preserve the line of sight with the LookAt target of the virtual camera by moving away from objects that will obstruct the view.

Additionally, the Collider can be used to assess the shot quality and report this as a field in the camera State.

SoftZone/DeadZone

Tune these to define where you want the subject to be on-screen. These controls are incredibly versatile. The blue areas are the ‘squishy’ areas based on how much horizontal/vertical damping you have, and the red areas define the ‘no pass’ limits where the camera will always track the subject. Opening up the soft areas to create a ‘dead zone’ in the middle allows you to make areas of the screen immune to target motion, handy for things like animation cycles where you don’t want the camera to track the target if it moves just a little.

Dead Zone Width

The camera will not rotate horizontally if the target is within this range of the position.

Dead Zone Height

The camera will not rotate vertically if the target is within this range of the position.

Soft Zone Width

When a target is within this region, the camera will gradually rotate horizontally to re-align towards the desired position, depending on the damping speed.

Soft Zone Height

When a target is within this region, the camera will gradually rotate vertically to re-align towards the desired position, depending on the damping speed.

Cinemachine Confiner

An add-on module for Cinemachine Virtual Camera that post-processes the final position of the virtual camera. It will confine the virtual camera’s position to the volume specified in the Bounding Volume field.

This is less resource-intensive than CinemachineCollider, but it does not perform a shot evaluation.

The Confiner can operate in 2D or 3D mode. The mode will influence the kind of bounding shape it will accept. In 3D mode, the camera’s position in 3D will be confined to the volume. This will work for 2D games, but you will have to take the depth into account. In 2D mode, you don’t have to worry about depth.

If your camera is orthographic, there will be an additional option to confine the screen edges, not just the camera point. This ensures that the entire screen area stays within the bounding shape.

Помогаем камерам в фильмах и играх

Получившая награду «Эмми» система Cinemachine — это набор инструментов для создания динамических, умных, не требующих программирования камер, создающих лучшие кадры на основе композиции сцены и взаимодействия объектов в ней, что позволяет вам настраивать, разрабатывать, экспериментировать и задавать поведение камеры в реальном времени.

Воспользуйтесь пакетным менеджером Unity (в верхнем меню: Window > Package Manager), чтобы выбрать и установить Cinemachine. Если вы не видите этого пакета, найдите выпадающее меню над списком и выберите All packages.

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

Harold Halibut by Slow Bros

Cinemachine ускоряет разработку игр. Она освобождает вашу команду от разработки дорогостоящей логики поведения камер и позволяет сразу же разрабатывать и прототипировать новые идеи, одновременно сохраняя настройки в режиме Play. Модули камеры Cinemachine были доведены до совершенства за долгие годы использования в разных условиях, от шутеров с видом от первого лица до игр со следящей камерой, от 2D до 3D, от игр в реальном времени до кат-сцен.

Основное поведение

Composer

Настройте камеру так, чтобы она автоматически поворачивалась и следила за вашими объектами в любой точке экрана. Composer позволяет осуществлять процедурную компоновку в реальном времени, настраивать задержку следования, ширину/высоту заглушения и даже опережающий просмотр движения, чтобы профессионально управлять кадром.

Transposer

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

Обзорные камеры

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

Cinemachine для 2D

Cinemachine поддерживает насколько характерных для 2D функций, включая ортогональную отрисовку и 2D-кадрирование, с помощью которых вы сможете компоновать, отслеживать и следовать за объектами. Настройка мощной 2D-камеры крайне проста.

Target Groups

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

Пользовательские смешения

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

Расширенное управление

Impulse

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

Микшер

Изменяйте свои кадры, смешивая до 8 виртуальных камер, и управляйте смешением вручную с помощью Timeline или посредством кода. Микшер — это крайне гибкая система, где характеристики нескольких камер могут объединяться для создания идеального кадра в меняющихся условиях.

Коллайдер

С легкостью управляйте и автоматизируйте уклонение от стен и объектов любой камеры Cinemachine, не прибегая к программированию. Коллайдер позволяет использовать несколько способов удержания камеры от столкновения с объектами мира.

Ограничитель

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

Легко добивайтесь эффекта ручной съемки или добавляйте другие типы тряски камерам без необходимости создавать ключевые кадры, использовать пресеты или ручную настройку. Многоуровневая система шума Perlin в Cinemachine также снабжена визуальным дисплеем, на котором вы сможете увидеть, что именно происходит.

Приоритет

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

Разделенный экран и режим «картинка в картинке»

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

Следящее увеличение

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

Интеграция стека постобработки

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

Clear Shot

Всегда получайте отличные кадры. Если что-то встанет между персонажем или объектом, Clear Shot выберет самую подходящую камеру, в зависимости от оценки кадра. Эта функция отлично подходит для повторов или кат-сцен в изменяемыми сценариями.

Мощные функции

Разделенный экран и режим «картинка в картинке»

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

Следящее увеличение

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

Интеграция стека постобработки

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

Clear Shot

Всегда получайте отличные кадры. Если что-то встанет между персонажем или объектом, Clear Shot выберет самую подходящую камеру, в зависимости от оценки кадра. Эта функция отлично подходит для повторов или кат-сцен в изменяемыми сценариями.

Behind the Scenes on “Baymax Dreams”

Cinemachine — это ваш личный оператор-постановщик, знающий куда направить камеру и на чем сфокусироваться. Экспериментируйте с тележками для камер, слежением, тряской и постэффектами в реальном времени. Все выполняется процедурно, поэтому изменения просто срабатывают. Вы даже можете вносить изменения в анимации после разметки — Cinemachine знает, какие кадры вам нужны, и автоматически подстраивается, даже если события в кадре изменятся. Cinemachine получила премию «Эмми» за революцию в области кинематографии.

Мощные функции, полностью меняющие разметку CG

Composer

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

Transposer

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

Постобработка

Постобработка, цветокоррекция, эмуляция линз, глубина поля и многое другое — в реальном времени для каждого кадра. Если вы измените редактуру, цветокоррекция изменится вместе с ней. Смешивайте кадры на Timeline, и все остальное тоже смешается. Новый, функциональный и крайне быстрый метод работы.

Смешивание кадров

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

Следящее увеличение

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

Наборы линз

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

Cinemachine. If you’re not. You should.

ForrestAtSunset_01.PNG

So full disclosure! This isn’t intended to be the easy one-off tutorial showing you how to make a particular thing. I want to get there, but this isn’t it. Instead, this is an intro. An overview.

If you’re looking for “How do I make an MMO RPG RTS 2nd Person Camera” this isn’t the tutorial for you. But! I learned a ton while researching Cinemachine (i.e. reading the documentation and experimenting) and I figured if I learned a ton then it might be worth sharing. Maybe I’m right. Maybe I’m not.

Cinemachine. What is it? What does it do?

Cinemachine setup in the a Unity scene

Cinemachine is a Unity asset that quickly and easily creates high-functioning camera controllers without the need (but with the option) to write custom code. In just a matter of minutes, you can add Cinemachine to your project, drop in the needed prefabs and components and you’ll have a functioning 2D or 3D camera!

It really is that simple.

If you’re like me you may have just fumbled your way through using Cinemachine and never really dug into what it can do, how it works, or the real capabilities of the asset. This leaves a lot of potential functionality undiscovered and unused.

Like I said above, this tutorial is going to be a bit different, many other tutorials cover the flashy bits or just a particular camera type, this post will attempt to be a brief overview of all the features that Cinemachine has to offer. Future posts will take a look at more specific use cases such as cameras for a 2D platformer, 3rd person games, or functionality useful for cutscenes and trailers.

If there’s a particular camera type, game type, or functionality you’d like to see leave a comment down below.

How do you get Cinemachine?

Cinemachine in the PAckage Manager

Cinemachine used to be a paid asset on the asset store and as I remember it, it was one of the first assets that Unity purchased and made free for all of its users! Nowadays it takes just a few clicks and a bit of patience with the Unity package manager to add Cinemachine to your project. Piece of cake.

The Setup

Once you’ve added Cinemachine to your project the next step is to add a Cinemachine Brain to your Unity Camera. The brain must be on the same object as the Unity camera component since it functions as the communication link between the Unity camera and any of the Cinemachine Virtual Cameras that are in the scene. The brain also controls the cut or blend from one virtual camera to another — pretty handy when creating a cut scene or recording footage for a trailer. Additionally, the brain is also able to fire events when the shot changes like when a virtual camera goes live — once again particularly useful for trailers and cutscenes.

Cinemachine does not add more camera components to your scene, but instead makes use of so-called “virtual cameras.” These virtual cameras control the position and rotation of the Unity camera — you can think of a virtual camera as a camera controller, not an actual camera component. There are several types of Cinemachine Virtual Cameras each with a different purpose and different use. It is also possible to program your own Virtual Camera or extend one of the existing virtual cameras. For most of us, the stock cameras should be just fine and do everything we need with just a bit of tweaking and fine-tuning.

Cinemachine offers several prefabs or presets for virtual camera objects — you can find them all in the Cinemachine menu. Or if you prefer you can always build your own by adding components to gameObjects — the same way everything else in Unity gets put together.

As I did my research, I was surprised at the breadth of functionality, so at the risk of being boring, let’s quickly walk through the functionality of each Cinemachine prefab.

Virtual Cameras

Bare Bones Basic Virtual Camera inspector

The Virtual Camera is the barebones base virtual camera component slapped onto a gameObject with no significant default values. Other virtual cameras use this component (or extend it) but with different presets or default values to create specific functionality.

The Freelook Camera provides an out-of-the-box and ready-to-go 3rd person camera. Its most notable feature is the rigs that allow you to control and adjust where the camera is allowed to go relative to the player character or more specifically the Look At target. If you’re itching to build a 3rd person controller — check out my earlier video using the new input system and Cinemachine.

The 2D Camera is pretty much what it sounds like and is the virtual camera to use for typical 2D games. Settings like softzone, deadzone and look ahead time are really easy to dial in and get a good feeling camera super quick. This is a camera I intend to look at more in-depth in a future tutorial.

The Dolly Camera will follow along on a track that can be easily created in the scene view. You can also add a Cart component to an object and just like the dolly camera, the cart will follow a track. These can be useful to create moving objects (cart) or move a (dolly) camera through a scene on a set path. Great for cutscenes or footage for a trailer.

“Composite” Cameras

The word “composite” is my word. The prefabs below use a controlling script for multiple children cameras and don’t function the same as a single virtual camera. Instead, they’re a composite of different objects and multiple different virtual cameras.

Some of these composite cameras are easier to set up than others. I found the Blend List camera 100% easy and intuitive. Whereas the Clear Shot camera? I got it working but only by tinkering with settings that I didn’t think I’d need to adjust. The 10 minutes spent tinkering is still orders of magnitude quicker than trying to create my own system!!

The Blend List Camera allows you to create a list of cameras and blend from one camera to another after a set amount of time. This would be super powerful for recording footage for a trailer.

Blend List Camera

The State-Driven Camera is designed to blend between cameras based on the state of an animator. So when an animator transitions, from say running to idle, you might switch to a different virtual camera that has different settings for damping or a different look-ahead time. Talk about adding some polish!

The ClearShot Camera can be used to set up multiple cameras and then have Cinemachine choose the camera that has the best shot of the target. This could be useful in complex scenes with moving objects to ensure that the target is always seen or at least is seen the best that it can be seen. This has similar functionality to the Blend List Camera, but doesn’t need to have timings hard coded.

The Target Group Camera component can act as a “Look At” target for a virtual camera. This component ensures that a list of transforms (assigned on the Target Group Camera component) stays in view by moving the camera accordingly.

Out of the Box settings with Group Target — Doing its best to keep the 3 cars in the viewport

The Mixing Camera is used to set the position and rotation of a Unity camera based on the weights of its children’s cameras. This can be used in combination with animating the weights of the virtual cameras to move the Unity camera through a scene. I think of this as creating a bunch of waypoints and then lerping from one waypoint to the next. Other properties besides position and rotation are mixed.

Ok. That’s a lot. Take a break. Get a drink of water, because that’s the prefabs, and there’s still a lot more to come!

Shared Camera Settings

There are a few settings that are shared between all or most of the virtual cameras and the cameras that don’t share very many settings fall into the “Composite Camera” category and have children cameras that DO share the settings. So let’s dive into those settings to get a better idea of what they all do and most importantly what we can then do with the Cinemachine.

All the common and shared virtual camera settings

The Status line, I find a bit odd, it shows whether the camera is Live, in Standby, or Disabled which is straightforward enough, but the “Solo” button next to the status feels like an odd fit. Clicking this button will immediately give visual feedback from that particular camera, i.e. treating this camera as if it is the only or solo camera in the scene? If you are working on a complex cutscene with multiple cameras I can see this feature being very useful.

The Follow Target is the transform for the object that the virtual camera will move with or will attempt to follow based on the algorithm chosen. This is not required for the “composite” cameras but all the virtual cameras will need a follow target.

The Look At Target is the transform for the object that the virtual camera will aim at or will try to keep in view. Often this is the same as the Follow Target, but not always.

The Standby Update determines the interval that the virtual camera will be updated. Always, will update the virtual camera every frame whether the camera is live or not. Never, will only update the camera when it is live. Round Robin, is the default setting and will update the camera occasionally depending on how many other virtual cameras are in the scene.

The Lens gives access to the lens settings on the Unity camera. This can allow you to change those settings per virtual camera. This includes a Dutch setting that rotates the camera on the z-axis.

The Transitions settings allow customization of the blending or transition from one virtual came to or from this camera.

The Body controls how the camera moves and is where we really get to start customizing the behavior of the camera. The first slot on the body sets the algorithm that will be used to move the camera. The algorithm chosen will dictate what further settings are available.

It’s worth noting that each algorithm selected in the Body works alongside the algorithm selected in the Aim (coming up next). Since these two algorithms work together no one algorithm will define or create complete behavior.

The transposer moves the camera in a fixed relationship to the follow target as well as applies an offset and damping.

The framing transposer moves the camera in a fixed screen-space relationship to the Follow Target. This is commonly used for 2D cameras. This algorithm has a wide range of settings to allow you to fine-tune the feel of the camera.

The orbital transposer moves the camera in a variable relationship to the Follow Target, but attempts to align its view with the direction of motion of the Follow Target. This is used in the free-look camera and among other things can be used for a 3rd person camera. I could also imagine this being used for a RTS style camera where the Follow Target is an empty object moving around the scene.

The tracked dolly is used to follow a predefined path — the dolly track. Pretty straightforward.

Dolly track (Green) Path through a Low Poly Urban Scene

Hard lock to target simply sticks the camera at the same position as the Follow Target. The same effect as setting a camera as a child object — but with the added benefit of it being a virtual camera not an actual Unity camera component that has to be managed. Maybe you’re creating a game with vehicles and you want the player to be able to choose their perspective with one or more of those fixed to the position in the vehicle?

The “do nothing” transposer doesn’t move the camera with the Follow Target. This could be useful for a camera that shouldn’t move or should be fixed to another object but might still need to aim or look at a target. Maybe for something like a security-style camera that is fixed on the side of a building but might still rotate to follow the character.

The Aim controls where the camera is pointed and is determined by which algorithm is used.

The composer works to keep the Look At target in the camera frame. There is a wide range of settings to fine-tune the behavior. These include look-ahead time, damping, dead zone and soft zone settings.

The group composer works just like the composer unless the Look At target is a Cinemachine Target Group. In that case, the field of view and distance will adjust to keep all the targets in view.

The POV rotates the camera based on user input. This allows mouse control in an FPS style.

The “same as follow target” does exactly as a says — which is to set the rotation of the virtual camera to the rotation of the Follow target.

“Hard look at” keeps the Look At target in the center of the camera frame.

Do Nothing. Yep. This one does nothing. While this sounds like an odd design choice, this is used with the 2D camera preset as no rotation or aiming is needed.

Noise

The noise settings allow the virtual camera to simulate camera shake. There are built-in noise profiles, but if that doesn’t do the trick you can also create your own.

Extensions

Cinemachine provides several out-of-the-box extensions that can add additional functionality to your virtual cameras. All the Cinemachine extensions extend the class CinemachineExtension, leaving the door open for developers to create their own extensions if needed. In addition, all existing extensions can also be modified.

Cinemachine Camera Offset applies an offset to the camera. The offset can be applied after the body, aim, noise or after the final processing.

Cinemachine Recomposer adds a final adjustment to the composition of the camera shot. This is intended to be used with Timeline to make manual adjustments.

Cinemachine 3rd Person Aim cancels out any rotation noise and forces a hard look at the target point. This is a bit more sophisticated than a simple “hard look at” as target objects can be filtered by layer and tags can be ignored. Also if an aiming reticule is used the extension will raycast to a target and move the reticule over the object to indicate that the object is targeted or would be hit if a shot was to be fired.

Cinemachine Collider adjusts the final position of the camera to attempt to preserve the line of sight to the Look At target. This is done by moving the camera away from gameObjects that obstruct the view. The obstacles are defined by layers and tags. You can also choose a strategy for moving the camera when an obstacle is encountered.

Cinemachine Confiner prevents the camera from moving outside of a collider. This works in both 2D and 3D projects. It’s a great way to prevent the player from seeing the edge of the world or seeing something they shouldn’t see.

Polygon collider setting limits for where the camera can move

Cinemachine Follow Zoom adjusts the field of view (FOV) of the camera to keep the target the same size on the screen no matter the camera or target position.

Cinemachince Storyboard allows artists and designers to add an image over the top of the camera view. This can be useful for composing scenes and helping to visualize what a scene should look like.

Cinemachine Impulse Listener works together with an Impulse Source to shake the camera. This can be thought of as a real-world camera that is not 100% solid and has some shake. A source could be set on a character’s feet and emit an impulse when the feet hit the ground. The camera could then react to that impulse.

Cinemachine Post Processing allows a postprocessing (V2) profile to be attached to a virtual camera. Which lets each virtual camera have its own style and character.

There are probably even more… but these were the ones I found.

Conclusion?

Cinemachine is nothing short of amazing and a fantastic tool to speed up the development of your game. If you’re not using it, you should be. Even if it doesn’t provide the perfect solution that ships with your project it provides a great starting point for quick prototyping.

If there’s a Cinemachine feature you’d like to see in more detail. Leave a comment down below.

Камера Cinemachine — настоящая кинокамера для игр и фильмов

Cinemachine Collider

Установить Cinemachine очень просто из пакетного менеджера Unity (в верхнем меню: Window -> Package Manager), и найти Cinemachine. Если не видно пакета, над списком в выпадающем меню надо выбрать «All packages». Камера Cinemachine бесплатна и доступна для любого проекта.

После установки, будет доступен основной компонент Синемашин (Cinemachine) — это скрипт «Cinemachine Brain», устанавливаемый на основную камеру. Он позволит создавать и контролировать множество виртуальных камер пакета Синемашин. Это настоящие кинокамеры с разнообразным поведением!

Cinemachine Brain

Скрипт «Cinemachine Brain»

Настройка Cinemachine

После этого мы перетаскиваем камеру на Таймлайн (Timeline) и выбираем «Cinemachine Track».

Cinemachine Track

Создание дорожки для управления поведением камеры

После добавляем «Cinemachine Shot Clip».

Cinemachine Shot Clip

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

Create Cinemachine Virtual Camera

Создание виртуальной камеры Cinemachine

В поле «Virtual Camera» можно выбрать любую подходящую камеру или создать новую. После нажатия кнопки создать, мы получим новую виртуальную камеру Синемашин в иерархии и сможем перейти к её настройке и использованию.

Cinemachine Look At

Выбор поведения камеры Cinemachine

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

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

Dolly Camera

Dolly Camera

Синемашин также представляет вам возможность создавать различные по типу камеры, в том числе «Dolly Camera», которая позволит перемещаться не просто следуя за объектом, а двигаться по заранее настроенному пути. Совсем как в кино!

Камера Cinemachine и постпроцессинг (Post Processing)

Cinemachine Post Processing

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

Камера Синемашин (Cinemachine) для 2D

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

Например, при использовании на виртуальной камере компонента «Cinemachine Confiner» возможно создать коллайдер (Collider) за пределы которого камера не выйдет, если персонаж упрётся в рамки уровня.

Cinemachine Collider

Использование Cinemachine в Unity сбережёт кучу времени начинающим разработчикам. А для многих инди-разработчиков будет вариантом, возможностей которого хватит с лихвой.

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

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