Камера в Unity — следовать, но не вращаться
Есть объект, если камера которая следует за ним. Как сделать, чтобы эта камера следовала, но не вращалась за объектом? Вешал Rigidbody на камеру,фризил его вращения — не помогает.
Самое банальное это просто брать старые координаты и добавлять смещение, сделанное игроком.
![]()
- В Hierarchy привязать камеру к объекту
- В Inspector (камера) добавить компоненты: Distance Joint 2D и Rigibody 2D
- В Inspector-Distance Joint 2D (камера) привязать объект на Connected Rigid Body
- В Inspector-Rigibody 2D (камера) установить минимальное значение Mass (0.0001) и включить Constraints-Freeze Rotation Z
- В Scene отцентровать камеру с объектом
P.s. Это упрощенный вариант без применения скриптов
Как вариант: помести обьект в камеру как дочерний. Но тогда будет проблема если нужно вращать камеру — ведь обьект будет вращатся если вращать камеру.
Как второй вариант: напиши простенький скрипт который запоминает разницу между координатами обьекта и камеры на инициализации и в каждом апдейте просто меняй трансформ.Позишн на данную разницу.
Движение камеры за персонажем [2D платформер]
Сегодня напишем скрипт, который предназначен для того, чтобы камера следовала за объектом. Прежде всего, данный скрипт заточен под платформер, где игрок управляет неким персонажем. Например, как в игре Mario и подобные, важно то, что персонаж должен перемещаться влево или вправо, по оси икс. Камера будет плавно двигаться вслед за объектом, а также определять в какую сторону в данный момент движется объект. Это нужно, чтобы добавить смещение по иксу, то есть, если персонаж смотрит допустим вправо, то камера будет сдвинута немного вправо и вверх, если добавлено смещение по вертикали.
Чтож, создаем скрипт CameraFollow2D:
damping — регулируем плавность движения камеры.
offset — добавить смещение по вертикали и горизонтали.
faceLeft — если изначально персонаж «смотрит» влево, ставим галочку.
Чтобы всё работало, тот объект, которым управляет игрок, должен иметь стандартный тег Player. Стоит обратить внимание на функцию FindPlayer, к ней нужно обращаться каждый раз, когда используется респаун объекта, кроме того, учитывается и то, в какую сторону «смотрит» объект по умолчанию, например, FindPlayer(true), если «смотрит» влево. Здесь важно понимать, что суть не в том, куда смотрит персонаж во время перемещения, а то, в какую сторону движется объект, влево или вправо. Если вы хотите жесткую привязку, относительно лица, тогда надо удалить все строки с обработкой переменных lastX и currentX. А переменную faceLeft сделать статической:
Unity 2D How to Make the Camera Follow Player – Easiest Method
So you have a game either in 2d or 3d which you need the camera to follow the player. In this tutorial we will be discussing the different methods how you can use unity 2d and how to make the camera follow the player in your game. We will look at basic principles of doing this in unity 2d.
Then to do this in 3d is very similar, you will just make use of the z axis as well depending on the view you have in your game.
Whether that be top down, side scrolling or first or third person.
Rather want to watch video, here is the video version of this tutorial.

We will start off by adding a simple player as a square sprite.
So go ahead and right click in our assets folder and create a square sprite with the below steps in the screenshots.

Rename our square to player.

Next lets add some components. We want to drag our sprite into our scene.

Now go ahead and add a rigidbody2d component on the right by clicking on add component. Then change the rigidbod2d settings to be kinematic.

Once done let’s create a player movement script.

Call that player movement.

Drag and drop that onto your player game object like so.

Now go ahead and open up the player movement script in visual studio. Replace the code in that script with this.
Now you should have a moving player when you hit play in unity. Let’s just add a basic background. I made this one in inkscape very quickly.

So dragging that into our unity project we now have.

Simplest player camera follow and movement
The simplest way to do a camera follow is to just child our camera to our player like this.

So if you have done this and you have moved your player to the edge of the screen you have probably figured out that this is not the most efficient way.
As your player may be able to go out of the bounds of the screen and so will your camera view. So you will end up with something like this.

So with this method we have very little control over our camera’s transform, it’s all dependent on the player transform.
A better method is for us to rather use a script.
Unity 2d player follow and camera movement script
So go ahead and create a new c# script and call it camera follow like this.

Open that up in c# and use this script below. I will explain how this works afterwards.
In it’s most basic form this is what you will need to make the camera follow your player with a script. So simply put we declare a followTransform, this will be a our player’s transform we will be following with our camera.
We then in fixedupdate change our camera transform position to that of our player only on the x and y axis because we are moving in 2d space.
Go ahead now save this and add this to your camera. Like so:

Also drag your player into the follow transform slow like above. If you run your player camera follow project now your camera should be following your player.
Well this is only half the story. Let us now implement some camera bounds so our player won’t go outside our background.
Unity 2d camera bounds
To create a camera bounds you firstly need to create a way of measuring bounds. You can do this on our background which we want to restrict our camera follow on. So go over to your bg or background game object and add in a boxcollider2d.

With the boxcollider2d added we now have a way of getting the bounds of our background scene. So let’s now add some c# code to our camera follow script and make it restrict the bounds on our camera.
This may seem very complicated when you first look at. However it is quite simple. First thing we added to our script is to get our mapBounds which is a boxcollider2d which have declared as public.
We then declare a few float variables for our xMin,xMax,yMax,yMin these will hold our min and max bounds from our boxcollider2d. Then we create a camX and camY variable to control our camera movement.
We declare camOrthsize which will hold our vertical size of our camera field of view. This translates to half of that size in world space.
There is also a cameraRatio variable which will determine our horizontal camera ratio or orthographic size.
We finally then declare a camera variable to hold our main camera.
In the start method we set out bounds variables. We get our camera component to get our main camera.
After this we get the orthographic size of our camera.
Then we calculate the horizontal size based off the half size of the camera ortho and add that to the maximum size on the x of our bounds and simply divide that by 2.
We now know how far we can move on the x axis before our camera will go out of view. We divide specifically by 2.0f to keep the calculation as a float value so we don’t lose precision.
Finally in our fixedupdate method we clamp down our variables and offset them by the half size of our camera ortho by adding and subtracting them to their relevant positions.
You may need to go through this script a few times to full understand. Once you got that down. Make you add your script to your camera in unity.

As well as dragged your background into the map bounds slot.
When you run this you should end up with something that functions like this.

So as you see your player will approach the bounds and the camera will stop following at that point.
If you have done all this correctly you should have a script which allows the camera to follow the player to the T in both position and rotation.
Adapting this for unity 2d platformer movement
This is actually very simple. With what you have here you will be able to do this just fine. You may want to just add some smoothing with your camera movement though.
You can do this using a lerp function. So here is how we will modify the c# script to make the player camera follow movement smooth.
Simply we will add a smoothPos and a smoothSpeed variable. Then in our fixedupdate method we will take our current position, pass in our clamped position and lerp at the smooth speed.
This will give us that smooth camera movement you will need in your 2d platformer game.
Unity camera movement Q&A
Unity 2d how to make camera follow player?
There are a few methods of doing this. One of which is to parent your camera to your player. This is the most simple method. The other is to use a c# script to control the camera movement. Another method is using features from cinemachine.
How to make camera follow player position and rotation unity 3d?
You can use a c# script to control the camera and make it move relative to the player transform. You can control this on the x,y and z axis to create different types of camera follows. Like top down, side scrolling, 3rd person and 1st person camera follows.
How to make the unity camera follow behind player?
The simplest method is to parent your main camera to your player and offset it’s position slightly behind the player. For more advanced camera follows you may want to use a c# script to control the camera.
How do I add unity 2d camera bounds?
To do this you need to create a bounding box which you can get the bounds from. Then restrict your camera transform using mathf.clamp and keep it within the bounds of the bounding box.
Some last words
If you liked this tutorial. Please consider sharing it on social media or supporting me on youtube by subscribing to my channel here: Subscribe on YouTube. Also consider checking out my course on building a unity 3d city builder here: Course. Check out some of my other blog posts and tutorials here:
Создание эффекта плавной камеры, следующей за объектом — краткий туториал Статьи редакции
Поэтапное описание реализации эффекта с примером кода.
Пользователь Reddit под ником Awsomelity опубликовал короткий туториал для Unity, в котором показал, как сделать камеру, плавно следующую за объектом. Автор представил код, а также подробно показал все этапа реализации этого эффекта.
На сцене вам понадобится лишь несколько объектов: направленный свет, плоскость, предмет и камера. Сперва нужно создать скрипт.
Затем прикрепите скрипт к камере и откройте его. В этом окне удалите ненужную часть кода.
Затем вам нужно добавить переменную «object» — это объект, за которым следует камера, а также переменную «distanceFromObject» — дистанция камеры относительно объекта. Для этого добавьте следующий код:
Затем нужно добавить функцию «LateUpdate».
Новая часть кода:
Пора добавлять новые переменные: «positionToGo» — переменная, которая указывает на какую позицию переместится камера, «smoothPosition» определяет, насколько плавным будет перемещаться камера. Показатель «t:0.125F» определяет скорость движения камеры — вы можете замедлить или ускорить её, меняя значение. Пример кода:
Затем перетащите камеру, чтобы установить её базовое положение относительно объекта. Когда вы сделаете это, перенесите значение в поле «Distance From Object», которое находится в окне Inspector.
На этом этапе эффект плавной камеры выглядит вот так:
Но это пока не финальная версия эффекта. Теперь нужно сделать так, чтобы камера поворачивалась за объектом. Для этого достаточно всего одной строчки кода:
Вот так выглядит финальная версия эффекта:
Даже по последней гифке видно, что камера нифига не плавно поворачивает.
Автору стоит почитать и понять то как работает lerp, в его варианте каждый вызов ф-ии LateUpdate будет перемещать камеру на 12.5% от требуемого смещения. И чем дальше и быстрее обьект будет удаляться от камеры тем более вырвиглазно это будет выглядеть.
К тому же, константное значение dt в лерпе делает его fps-независимым => на разных fps, результат будет выглядеть по разному.