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

от admin

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

Получившая награду «Эмми» система 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 позволяют составить список любимых линз в выпадающем меню. Добавьте своему проекту последовательности, ограничив фокусные расстояния набором пресетов, как это делается на съемочной площадке.

Name already in use

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Smart camera tools for passionate creators

Cinemachine is a suite of modules for operating the Unity camera. Cinemachine solves the complex mathematics and logic of tracking targets, composing, blending, and cutting between shots. It is designed to significantly reduce the number of time-consuming manual manipulations and script revisions that take place during development.

Cinemachine default branch is main and that’s where the latest version of Cinemachine lives. For all other minor versions of Cinemachine, a new branch is created under release (e.g. release/2.9, release/2.8). These branches are maintenance branches.

During development, PRs are merged directly on main and maintenance branches. Those branches should always be shippable: the code compiles, features are complete and the CI pipeline is green.

Once a release is done, a branch with the version name is created under releases (e.g. releases/2.9.4, releases/3.0.0-pre.1). No changes are made to those branches. They exist for reference only.

Cinemachine is a supported package from Unity, and as such, can be installed from the official registry in the package manager of the Unity editor. The Cinemachine Release Procedure is an internal document that contains different information to help with the release of a new version of Cinemachine.

Understanding Unity Cinemachine – Advanced Camera Tutorial

In this lesson, we’re going to look at Cinemachine.

Cinemachine allows us to create more complex camera movements, tracking, and following targets by simple drag-and-drop methods.

If you haven’t already installed the Cinemachine package from the Package Manager, refer to Lesson 3 – Project Setup.

Creating Virtual Camera

Click on the Cinemachine dropdown from the top bar and select Create Virtual Camera.

Virtual Camera

It will then create a new GameObject called “CM vcam1“.

Game Object

You’ll notice that there’s a red camera icon next to our Main Camera. This indicates that the camera object has the CinemachineBrain component attached to it.

Cinemachine Brain component

The component is what we attach to a camera to utilize it with the Cinemachine system. For now, we’ll leave it at its default settings.

Virtual Camera Settings

Let’s have a look at the CinemachineVirtualCamera component attached to “CM vcam1”.

Virtual Camera Settings

The CinemachineVirtualCamera component is what defines the properties and actions of the specific camera. For example, you can easily set the target to follow or look at in the Inspector.

Virtual Camera Inspector

And then, we can modify the details, such as how closely it follows the target with some offsets, damping, smoothness, noise, and more.

properties offsets damping smoothness noise

The camera instantly snaps onto the ship’s position if you drag our Ship object into the LookAt field.

LookAt field

Ship object

But the camera is looking a bit too low now, so we can fix that by adjusting the Tracked Object Offset (Y-Axis) field under the Aim header.

Tracked Object Offset

ship object play

Aim Properties

The Lookahead properties allow the camera to calculate where the target will be moving to and adjust the offset based on the prediction.

Aim Properties

The Damping properties define how responsively the camera tries to maintain the offset in each axis. Small numbers make the camera more responsive. Larger numbers make the camera respond more slowly.

Damping properties

The Screen X, Y properties rotate the camera around the selected axis.

Screen X, Y properties

Dead Zone refers to the outermost region of the screen, in which the camera ignores any movement of the target.

Dead Zone

We can set the Dead Zone Width and Height so that the camera ignores minor target movement within the Dead Zone region.

Dead Zone Width and Height

Soft Zone is the blue area of the screen, which allows us for a smooth transition from the centre of the screen to the dead zone.

Soft Zone

If a target enters this region, the camera will re-orient to bring it back to the Dead Zone.

The Soft Zone properties and the Bias X, Y properties can be used to set the size and position of the Soft Zone.

Soft Zone properties

Finally, enabling the Center On Activate property means the camera will snap to the target as soon as the camera is initialized.

Cinemachine – Follow

In the previous lesson, we’ve set our Cinemachine Virtual Camera to look at our Ship GameObject. Now we’re going to make it follow the ship by assigning it to the Follow field.

Cinemachine virtual camera with Follow field filled

Let’s also adjust the camera’s position so that it looks like we’re looking at the stone from a first-person perspective.

camera position

 first person perspective

Let’s press Play to test it out. You’ll see that the camera tracks the stone while following the ship in a cinematic manner.

play ship

The Lens properties mirror their counterparts in the properties for the default Unity camera, such as Field of View, Orthographic Size, Clip Planes, etc.

 Lens properties

You can also choose to animate the Virtual Camera in Timeline instead of using the Follow property.

To change how the camera moves in the Scene, you can adjust the Body properties.

Body property

Transcript – Cinemachine – Look At

Hey, everyone, and welcome back. In this lesson, we are going to be looking at Cinemachine, what it does and how we can use it.

So, basically Cinemachine allows us to create much more complex camera movements, tracking, following around targets, and overall create nice cinematic camera movements and angles that would rather be quite hard to do without it, in code or in animation. So, Cinemachine just allows us to drag and drop components and make it quite easy and quick.

So, how do we begin? Well, we already installed the Cinemachine package from the package manager earlier on so make sure you have this Cinemachine selection at the top of the screen. And then once you do, you wanna click on Cinemamachine and then go ‘Create Virtual Camera’.

Now a few things happened. First of all, we have this brand new game object that got created called “CM vcam1” and if we look at our Main Camera over here in the hierarchy, you’ll see there’s a little icon next to it.

Now, if we click on Main Camera, you’ll see that we have our camera component, we have our audio listener but then we also have a brand new Cinemachine brain component. And this component is just what we attach to a camera in order to actually utilize it with the Cinemachine system.

Okay, so we don’t actually really have to modify anything here. This is all specific stuff, if you wanna change the update method, blending method, and all that, but generally, we can just close it up like so as we don’t need to touch any of those components. So let’s go over to the CM vcam1 and this, as you can see, has a Cinemachine virtual camera component.

And this is what defines sort of the properties and the actions of this specific camera, okay? Because with Cinemachine, you can have as many virtual cameras as you want, and then we can choose to toggle between them as we wish, okay?

So for example, here in the inspector, what we can do first of all, is we can choose to say, “Okay, I want you to follow this, and I want you look at this.” okay? So we can choose to follow a target and look at a target, and then we can modify those properties down here.

So we can modify how closely it follows the target with some offset, some dampening. We can then choose the aim settings, for example, do we want to look at a bit of an offset, do we wanna have a nice, smooth aim? And we can change a few other things as well, such as adding a noise and even some extensions here.

So, let’s just say, we have the ship currently sailing around. Let’s just say we want our camera to stay where it is right now but look at the ship as it sails around. Well, in that case, what we need to do is drag our ship into the “Look At” property right here. And as you can see, our camera has changed.

First of all, the camera has rotated to snap onto the ship’s position. Now the ship position originally is at its base, so that’s why we are looking towards the water here. And you’ll notice there is this sort of a box right here. This basically defines the range at which the camera is gonna sort of freely move, okay?

Читать:
Какие числа будут находиться в списке

Because we can define if it is a nice rigid look at, so we’re always looking at the exact position or if it’s a bit more natural and smooth. As if the camera is sort of tracking to keep up with the ship and we could of course modify all these properties. So, let’s just leave it as is right now and press play to see how it goes.

So as you can see, the ship goes off and we are rotating to face the camera. Okay, that was nice and easy. No code required at all. We can of course modify a few properties, if we go to our CM vcam1, let’s actually rename this one to ‘TrackCamera’. And if we go down to the “Aim” settings right here, we can change a few things.

First of all, let’s actually look at the ship a bit up more because right now, we’re looking a bit low. So where we have it ‘Tracked Object Offset’, we can raise this Y value a bit. And as you can see, we are now looking a bit above the ship’s position. So there we go.

We also have ‘Lookahead Time’, and watch what happens if I increase Lookahead Time and press play. As you can see, the camera is predicting where this ship is going to be. So we’re actually looking ahead of the ship. Now that can be useful in many cases, if you want a camera sort of looking ahead to see where an object’s going, it can be useful in those instances.

And we have ‘Lookahead Smoothing’. Now, as you can see, when we pressed play, it was quite rigid, Okay? We’re sort of snapping between the Lookahead positions, whereas if we increase the smoothing. As you can see, when we press play, it’s gonna be a nice, smooth transition between those points.

We can change on the fly as well. So, we can increase the smoothing and decrease it as we’re playing now, if you do want to modify those properties. We probably don’t want to look ahead time so we’ll bring that back down to zero. We also have the ‘Dampening’. Now Damping is basically adding smoothness to the camera movement, okay?

As you can see, if I bring the Damping down to zero on the horizontal and vertical axes and press play; you’ll see that we are basically stuck to this specific location on the ship, okay? It’s like in code. We were just telling the camera to look at this position on the ship and stay there every single frame.

But what if we want a bit of natural movement, as if there is actually a guy behind the camera sort of rotating it as the ship is moving? well, that’s when we can add in some Damping. So we can increase these values a bit. Probably don’t want to make it too high, otherwise the camera will take forever to catch up. Especially if it’s a fast moving object.

As you can see, the camera is now trying to keep up with the new position that we are trying to track. As you can see, there’s like a tiny little yellow square right here and that is the position the camera is trying to get to. And over time, based on the Damping and other settings, it will get there.

So I’m going to bring this back down to let’s just say, one, to make it nice, not too rigid but not too smooth. And then we have screen X and screen Y. And what this does is it kind of adds an offset to where we are looking or an offset to the screen. So as you can see, if I modify here on the X, you’ll see the camera is sort of rotating left and right.

And on the Y it rotates up and down, okay? Now this may be useful but we’re probably going to leave that at zero for now. Next up we have our ‘dead zone’, okay? Now the dead zone is basically the area of the screen that we are not going to track our object, okay?

And as you can see, if I increase the width and increase the height, you’ll see there is this box that appears in the middle of the screen, okay? It’s not blue and it’s not red. It’s sort of the transparent box. And if our point of reference right here, this yellow square that we’re trying to track.

If this is within this box right here, then we are not going to track our object. So watch what happens when I press play. You’ll notice that as long as this ship is within this box right here, it will not track it only when it leaves it, okay? So you can press play. And as you can see, now we start tracking it once it is outside of our dead zone.

Now this can be useful of course, in a game where you want the player to have the freedom of moving around but you don’t want the camera always stuck on them, okay? Maybe you only want them to start tracking them once they go off to the side of the screen.

We don’t really want this so we’re going to bring the dead zone back down to zero, so it’s always tracking our ship. And then we have our ‘Soft Zone width’ and ‘Soft Zone height’. Now Soft Zone is basically the area of the screen which allows us for this smooth transition, Okay? And this is basically this blue square here in the middle.

So if our point ever goes over to the red side of the screen, it’s basically going to stop right there, okay? So once we reach that point, we’re just going to snap onto a position and that’s so that the object doesn’t get too far off screen, It’s always going to be on screen.

‘Bias X’ and ‘Bias Y’ basically translates those changes and those zones are horizontally and vertically like so. And ‘Center On Active’ basically decides whether or not we’re going to snap to our ship when we start the game or when the camera is initialized.

So that is how we can set up a Cinemachine virtual Camera to start tracking and looking at an object as we move around in 3D space. Okay, in the next lesson, we are going to be looking at following our target because right now we have the camera looking at the target as it goes around the rock right here. We’ve looked for all these settings here.

Next lesson, we’re going to look at how we can actually attach this object, attach this camera to the ship, maybe as if there’s a cameraman on the ship, bobbing of the ship as it goes, okay? So thanks for watching and I’ll see you all in the next lesson.

Transcript – Cinemachine – Follow

Welcome back, everyone. In this lesson, we are going to be continuing on with looking at our Cinemachine virtual camera. So in the previous lesson, we looked at how we can actually look at an object over time. Okay.

So we’re having a camera rotate towards this ship. We have a bit of an offset, we have a bit of damping. Now, how do we actually get it to track the ship? How do we get it to actually follow the ship? Well, for this, we’re actually going to remove our look at reference right here.

So let’s just set this look at to none. So if we press play, you’ll see that our virtual camera isn’t doing anything right now and let’s get it to start actually following our ship. So I’m gonna drag ship into the follow property right here and straight away you can see that we’ve got a bit of a problem, okay.

Basically, if we go to the scene view, what’s happened here is that the camera has sort of snapped over to the position of the ship. Now, of course, if we open up body right here, we can add an offset so we can increase the Y a bit here.

Let’s actually set out rotation to zero, zero. So it is… Oh! Zero on the X and 180 on the Y. So it’s facing forward, like so, in the game view. We can then go ahead and add in some offset right here. So maybe we want it. We’ll just modify this a bit, a bit behind the ship. A bit to the left. So the camera is sort of on the left backside of the ship, like so.

We can even modify it a bit more. Okay. There we go. Maybe even a bit, add a bit of rotation Really it’s up to you. Now when we press play. We can have it follow the ship, like so. Okay. So you may notice that our ship, or our camera, doesn’t actually look at anything as the camera moves around, as the ship moves around.

So what we’re going to do is I’m actually going to set the look at here to not be the ship, but to be the stone right here, okay. So it’s going to look at the stone as the ship moves around, okay. We can change the offset of this a bit here. So we are looking. Oops. So we are looking at the stone position, move this over a bit like so.

We can then move the camera back a bit. So I’m going to get our camera. I’m going to move it about over. Let’s just say about here. Press play and look what happens. So as our ship moves, we are tracking the stone, like so. Okay. So it has a sort of a, maybe cinematic move. Maybe if the ship is circling around an object that it wants to focus on.

For example, if we’re having a ship fighting cut scene, we can have the camera tracking one ship while we’re looking at its target. We can also then go ahead and maybe increase the follow Y offset, like so. Press play again. So yeah, have a play around with these settings. There’s lots of different things that you can modify and add.

Now let’s also have a look at the lenses up here. Lens basically defines, we can define our field of view. So if we want a shallower depth of field, if we want to make a bit more cinematic, we can make it around 40 maybe. We can change our near and far clip planes. Probably don’t need to modify these.

As well as our Dutch angle, which rotates the screen left and right, like so. Okay. So we can have a lower field of view to maybe make it a bit, look a bit more like a cinematic camera Like so. You have the camera in the foreground, a rock in the background.

And in fact, we can probably move our camera back a bit here so we can add a position offset of Z a bit more something maybe like so. Okay. We can press play again, see how that looks. And yeah, there you go. So there’s a wide range of different camera moves and different things that you can do here.

You can have objects tracking. You can have objects moving over time. There’s also a large number of different cameras that you can create Right now, we’ve just looked at a virtual camera. There’s also a Dolly camera with track, which basically allows you to animate a camera to move along a predefined track.

So if you maybe have some characters walking through a hallway, or you have some sort of thing you want to track, but along a certain path, you can set that up. Cinemachine is quite an expansive package with so many different things. So I highly recommend that you just jump in, explore and just get creative.

So in the next lesson, we are going to be looking at Unity’s timeline, okay, and how we can start stitching together various different virtual cameras in order to create some sort of a cut scene, okay. Cutting between different camera angles.

We might have this one. We might have a camera on top of the rock. We might have a wide-angle camera that is just looking at the entire scene. And we’ll just be seeing how we can cut between those as well as doing some other stuff with the timeline as well. So thanks for watching and I’ll see you all in the next lesson.

Interested in continuing? Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!

Что такое Сinemachine в Unity?

Cinemachines

Cinemachines — Это крутой стандартный пакет от юнити, который управляет камерой в вашей игре.

Он может следить за персонажем, работать в катсценах, накладывать эффект дрожания камеры, делать движения камеры плавными, ограничивать ее движения в пространстве, делать «орбитальную» камеру для игры от 3-го лица, от первого лица и многое, многое другое.

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

Как сделать движение камеры за персонажем.

Начнем с самого часто необходимого, конечно, примеры я буду приводить с 2D игрой, так проще и понятнее.

Синемашина работает с «виртуальными» камерами, еще более виртуальными, чем камера в вашем проекте)

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

  1. Переходим в меню Window->Package Manager
  2. Ищем Cinemachine, если ее нет то нужно вверху окна выбрать «Unity registry»
  3. Жмем Install и ждем

Теперь пакет установлен и им можно пользоваться.

Находим в меню новый пункт и выбираем 2D Camera.

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

Выбираем созданный объект и указываем камере за кем нужно следовать.

Настройка синемашины(Cinemachine)

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

Что такое Сinemachine в Unity?

В принципе, камера уже следит за игроком, но ее конечно же, можно настроить как вам угодно.

Как настроить Cinemachine для 2D игры

Если ваш персонаж управляется физикой, то если приглядеться камера дергается при движении. Происходит это потому, что слежка камеры в данный момент происходит в Update, то-есть каждый кадр, а физика просчитывается в FixedUpdate, то-есть через определенные промежутки времени, нужно это исправить.

Жмем на MainCamera, на ней автоматически должен был создаться скрипт CinemachineBrain. И меняем Update method и Blend update method на FixedUpdate.

cinemachine дергается камера при движение. как исправить. ответ

Если дергается камера при движении

После этого камера будет адекватно себя вести.

Выбираем нашу ВИРТУАЛЬНУЮ камеру «CM vcam1«. Я хочу, что-бы камера обгоняла персонажа при движении и позволяла посмотреть немного вперед себя.

Для этого есть 3 пункта для настройки.

  1. Как далеко должна обгонять камера
  2. Как плавно она разгоняется
  3. Игнорирование смещений по вертикали

С этими настройками камера обгоняет игрока и дает посмотреть, что там впереди.

Далее идут настройки плавности отслеживания.

плавность

Плавность

Покрутив настройки можно добиться желаемой плавности перемещения камеры. Я оставлю как есть.

смещение

Смещение

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

Что такое Сinemachine в Unity?

Мертвая зона

Далее идет так называемая «мертвая зона», зона в которой камера не будет реагировать на движения игрока.

Что такое Сinemachine в Unity?

Ограничения мягкой зоны

Это настройка «мягкой зоны». Когда вы настраиваете плавность движения камеры, она может уплыть далеко от цели, что-бы этого не происходило, необходимо настроить эти параметры. Если в момент настройки находиться в окне режиме проигрывания игры, то все изменения будут видны сразу. Для сохранения настроек после выхода из игрового режима нужно поставить галочку выше.

Как сохранять настройки синемашины в игровом режиме

Сохранение настроек в режиме игры

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

Настройка тряски камеры

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

Похожие статьи