Создание эффекта плавной камеры, следующей за объектом — краткий туториал Статьи редакции
Поэтапное описание реализации эффекта с примером кода.
Пользователь Reddit под ником Awsomelity опубликовал короткий туториал для Unity, в котором показал, как сделать камеру, плавно следующую за объектом. Автор представил код, а также подробно показал все этапа реализации этого эффекта.
На сцене вам понадобится лишь несколько объектов: направленный свет, плоскость, предмет и камера. Сперва нужно создать скрипт.
Затем прикрепите скрипт к камере и откройте его. В этом окне удалите ненужную часть кода.
Затем вам нужно добавить переменную «object» — это объект, за которым следует камера, а также переменную «distanceFromObject» — дистанция камеры относительно объекта. Для этого добавьте следующий код:
Затем нужно добавить функцию «LateUpdate».
Новая часть кода:
Пора добавлять новые переменные: «positionToGo» — переменная, которая указывает на какую позицию переместится камера, «smoothPosition» определяет, насколько плавным будет перемещаться камера. Показатель «t:0.125F» определяет скорость движения камеры — вы можете замедлить или ускорить её, меняя значение. Пример кода:
Затем перетащите камеру, чтобы установить её базовое положение относительно объекта. Когда вы сделаете это, перенесите значение в поле «Distance From Object», которое находится в окне Inspector.
На этом этапе эффект плавной камеры выглядит вот так:
Но это пока не финальная версия эффекта. Теперь нужно сделать так, чтобы камера поворачивалась за объектом. Для этого достаточно всего одной строчки кода:
Вот так выглядит финальная версия эффекта:
Даже по последней гифке видно, что камера нифига не плавно поворачивает.
Автору стоит почитать и понять то как работает lerp, в его варианте каждый вызов ф-ии LateUpdate будет перемещать камеру на 12.5% от требуемого смещения. И чем дальше и быстрее обьект будет удаляться от камеры тем более вырвиглазно это будет выглядеть.
К тому же, константное значение dt в лерпе делает его fps-независимым => на разных fps, результат будет выглядеть по разному.
How to make the camera follow an object in Unity3D
In this tutorial, we are going to learn how we can make the camera follow an object in Unity3D using two different methods. The first one is by writing a script that updates the position of the camera according to position of the object. The second one is using Cinemachine component of Unity3D.
A Little Bit Vector Algebra
Before we start writing our CameraFollow script, first we need to review our knowledge about vectors a little bit. If you are already familiar with vector algebra, you may skip this part. As you probably know, we represent positions of objects in Unity3D using vectors. In 2D space, we need 2 numbers to represent a position. Likewise, for 3D space, we need 3 numbers. To make it simple, for now, we are going to study in 2D space first, then move our discussion to 3D space.
As we mentioned above, in 2D space we need two numbers to represent a position. For instance, A=(2,3) represents a point on 2D space such that 2 units on the x-axis, and 3 units on the y-axis. In the same way, B=(2,-1) represents another vector.

Vectors are cool mathematical objects that you can perform several mathematical operations like summation, subtraction, different kind of multiplications, etc. If you would like to deep dive into game development, you should definitely be comfortable if you are not familiar with them. But for this tutorial, we are only going to cover basic operations.



Assume that you are at the center of the coordinate space. This point is called as the origin. And the coordinates of the origin are (0,0) in 2D space. Now assume that you are walking on the vertical axis to the up direction( i.e y-axis) by 3 units and then in the right direction by 2 units. Your final position will be the point (2,3). Alternatively, you can walk along the A. The final position will be the same. Let’s say A1=(0,3) and A2=(2,0). As you may notice we can represent vector A as the summation of two vectors, A1+A2. When we want to sum two vectors, we sum the first components and obtain the first component of the final vector. Likewise, we have to add the second component of two vectors to obtain the second component of the final vector.
Similarly, we can add any two vectors to obtain a third vector. For instance, if we add vector B to vector A, we get C which represents another position in the 2D space.
In addition to summation, we can multiply vectors by numbers (furthermore, you can multiply a vector with another vector but this is out of our interest, here). For instance, we can multiply vector B by 2. In this case, we will get a vector that is represented as (4,-2). Furthermore, you can multiply a vector with a negative number. For example, if you multiply B with -1, then you will get (-2,1).
All of our discussion here can be generalized to higher dimensions. All the mathematics is the same for 3D space also.
Up to now, we made a review of the basics of vector algebra and we are going to use these operations while we are writing a camera follow script.
Following an Object using CameraFollow Script
First, we will start with a basic script then we will make it better. Let’s start.
Assume that we have an object at some position in our scene. Let’s say the position vector that represents its position is O. And we have a camera that is located at some point in the scene that is represented by a position vector C.

Our aim is to update the position of the camera according to the object’s position. Therefore, we have to determine the position of the camera according to the object’s position. To do this, we need the position vector from the object to the camera. We can obtain this relative position vector by subtracting O from C:

Therefore, we can determine the new position of the camera by adding this relative direction vector to the object’s instantaneous position.
Create a new script and change its name to CameraFollow. Assign this script to your main camera.
As mentioned above, we get the relative position vector by subtracting the target object’s initial position from the camera’s initial position. We add this offset vector to the object’s position vector to find the new position vector of the camera. Do not forget to assign the target object into your script from the inspector.
We can make it smoother if we use the Vector3.Lerp method. Lerp method is used for linear interpolation. If we update the position of the camera with a delay, we will obtain a smooth movement. If you add a smoothness variable, you can control the delay.
Let me explain linear interpolation for those who are not familiar with. Linear interpolation is a method that returns a value between two values. In the Vector3.Lerp method, we used three arguments. The first and second ones are position vectors and the third one is the interpolation value. Assume that the first vector is a zero vector and the second vector is (1,0,0). If the third value is 0.5 then Vector3.Lerp method will return a vector (0.5, 0, 0). Likewise, in our CameraFollow script, we used smoothness*Time.fixedDeltaTime. Therefore, in each FixedUpdate() method call, the position vector is updated a small amount. This will create a smooth movement.
And this is the result:
Let’s take our script a step further. Now, we would like to specify a few coordinates relative to the target object and switch the position of the camera to these specified coordinates.
To do this, we can declare an enum and therefore when we want to switch the relative position, we can specify one of the selections.
Following an Object Using Cinemachine
In the second part of this tutorial, we are going to see how we can follow an object using the cinemachine component. First, we need to download and import the cinemachine from the asset store. If you have problems with importing cinemachine, you may need to restart Unity.

Add the Cinemachine Brain component to your main camera. Cinemachine Brain is the control point for the virtual cameras that we will create.

Now we can create several virtual cameras, control the behaviors of them and switching between them. But for this tutorial, we will create only one virtual camera to show how we can make the camera follow an object.
Create a virtual camera from the Cinemachine menu.
Click on the newly created virtual camera. Arrange your camera position, rotation or other settings as if it is your main camera. Then assign your target object to the Follow slot. If you would like to rotate your camera according to your object, you can assign it to Look At slot, also.

You can fine-tune the delay of the camera behind the movement of the object by changing damping values in each direction.

Hello, my name is İsmail. I am an indie game developer. I have been developing digital games for five years. I have released several games. I have BS degrees in electrical engineering and physics. I love arts and science. The idea of creating worlds and experiences brought me to the game development which is also directly related to the arts and science.
You may also like.
How to Apply Force to an Object in Unity3D
by İsmail Çamönü · Published March 11, 2020 · Last modified October 17, 2020
What is MonoBehaviour?
October 17, 2020
by İsmail Çamönü · Published October 17, 2020
InvokeRepeating vs Coroutines: Run a method at certain time intervals
November 18, 2019
by İsmail Çamönü · Published November 18, 2019 · Last modified October 17, 2020
Unity3D: камеры от третьего лица
Камера является одним из самых важных элементов в 3D-игре. Он действует как глаза игрока, позволяя им видеть игровой мир с разных точек зрения. В Unity3D 3D-камера работает так же, как пленочная камера. Его можно панорамировать, наклонять и масштабировать для кадрирования сцен. Из этого туториала вы узнаете, как создавать несколько перспектив камеры от третьего лица.
Для вдохновения или для использования в качестве отправной точки для своей работы ознакомьтесь с некоторыми из самых популярных 3D-моделей на Envato Market. Или получите помощь один на один, выбрав один из сервисов 3D-дизайна и моделирования в Envato Studio.

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

Выполните следующие шаги для настройки проекта:
- Нажмите Файл> Новый проект
- Назовите папку вашего проекта Камеры от третьего лица
- Нажмите Создать
- Нажмите GameObject> Создать другой> Направленный свет
- Нажмите GameObject> Создать другое> Плоскость
- В Инспекторе найдите компонент Transform и измените положение X на 0, Y на -0.5 и Z на 0, чтобы он находился ниже куба
- Скачать grid.png
- Перетащите grid.png на панель «Проект».
- Перетащите текстуру сетки с панели проекта на плоскость на панели иерархии.
- Выберите основную камеру, переместите и поверните ее в положение над и за кубом
- Сохраните свою сцену (Файл> Сохранить сцену) и назовите ее Main
Создать игрока
Все камеры, которые мы собираемся создать, будут нуждаться в цели: на что-то смотреть или следовать. Итак, давайте создадим основного игрока, которого мы можем перемещать с помощью клавиш со стрелками.
- Нажмите GameObject> Создать другое> Куб
- Переименовать его игрок
- В инспекторе убедитесь, что все координаты X, Y и Z установлены в ноль, поэтому мы уверены, что игрок находится в центре трехмерного мира.
- Нажмите Активы> Создать> C # Script
- Назовите скрипт Player
- Перетащите сценарий проигрывателя с панели «Проект» на проигрыватель на панели «Иерархия».
В сценарии Player добавьте два открытых свойства для движения и скорости поворота. Затем добавьте следующий код в ваш метод Update ():
Камера в Unity — следовать, но не вращаться
Есть объект, если камера которая следует за ним. Как сделать, чтобы эта камера следовала, но не вращалась за объектом? Вешал Rigidbody на камеру,фризил его вращения — не помогает.
Ответы (3 шт):
Как вариант: помести обьект в камеру как дочерний. Но тогда будет проблема если нужно вращать камеру — ведь обьект будет вращатся если вращать камеру.
Как второй вариант: напиши простенький скрипт который запоминает разницу между координатами обьекта и камеры на инициализации и в каждом апдейте просто меняй трансформ.Позишн на данную разницу.
Самое банальное это просто брать старые координаты и добавлять смещение, сделанное игроком.