Как отдалить камеру в юнити
Перейти к содержимому

Как отдалить камеру в юнити

How to zoom a camera in Unity (3 methods with examples)

Zoom a camera in Unity

Zooming a camera in and out is a commonly used mechanic in many different games.

A lot of the time, it’s a simple feature to create and to use.

While zooming a camera in Unity can be very straightforward, there are several different ways to do it, with each method producing a different type of zoom.

So, how do you zoom a camera in Unity?

There are 3 main methods for zooming a camera in Unity, with each method producing a different type of zoom effect:

  • Perspective Zoom, which works by changing a camera’s field of view to zoom the image in, giving the effect of looking through a telescope.
  • Movement Zoom, which involves physically moving a camera object closer to the subject, and can be used to adjust the position of a top-down camera or third-person camera.
  • 2D orthographic Zoom, which increases or decreases the viewable area of a 2D camera by changing its orthographic size.

Which method you use depends on what type of zoom effect you want to create and how you want it to work. In this article, you’ll learn the differences between each of the methods and how you can use them to add zoom features into your own game.

Here’s what you’ll find on this page:

Let’s get started.

How to zoom a camera in Unity (using field of view)

The basic method of zooming a camera in Unity can be very straightforward.

In fact, all you need to do to create a basic zoom effect is reduce the camera’s Field of View property.

Like this:

The field of view zoom effect, which works with cameras using the standard perspective projection mode, is similar to the effect of looking through a sniper scope or a telescope.

4x zoom using field of view in Unity

Changing the field of view produces a zoom effect similar to looking through a telescope.

Which makes it ideal for zooming in with weapons, first-person camera zoom or any type of zoom that aims to reproduce the effect of zooming in with a real lens.

There’s just one problem…

While adjusting the field of view property to create this type of zoom effect is appropriate, keep in mind that the effect is different than moving closer to an object, for example.

The field of view property in Unity relates, by default, to the vertical viewing angle of the camera, where increasing or decreasing the value changes the viewable area.

Reducing the angle reduces the size of the camera image which, when enlarged to fill the screen, creates the zoom effect.

Wide field of view angle Unity

A wide field of view shows more of the game world.

Narrow Field of view Unity

While a narrow field of view, shows less of the camera image, zooming it in.

For example, halving the camera’s field of view has the effect of 2x magnification, while dividing it by four will zoom the camera in by 4 times.

Which makes it ideal for lens-based zoom effects, like weapon zoom.

For example, you could use a field of view zoom to create a weapon zoom effect when the right mouse button is held down.

Like this:

In this basic example, the field of view property is set to half of a locally stored default value (which has been set to 90 degrees) to create a 2x zoom whenever the right mouse button is held down.

Why use a default setting?

You may have noticed that, in many games, you’re able to manually change the field of view setting, as increasing the field of view can help some players avoid motion sickness while reducing it can improve performance (since less of the game world is being rendered).

By changing the relative value, instead of setting a new, absolute viewing angle, you’ll be able to create a zoom effect that’s relative to the player’s view settings. So, for example, instead of zooming to a fixed field of view angle, you’ll be zooming to a multiplier of the player’s setting.

In this example, the field of view setting is instantly set to the new value, which snaps the camera to the new zoom level immediately.

Which in some cases, might be exactly what you want.

You might want to smooth the zooming motion so that, instead of happening immediately, the camera zooms in over an amount of time.

Here’s how to do that…

Smooth camera zoom in Unity

Generally, there are two ways to smoothly change a value in Unity.

By time, where the movement takes place over a fixed duration, and by speed, where the duration varies but the speed of the movement is always constant.

Smoothing a value by speed generally involves using the Move Towards function, which increments a value towards a target at a consistent rate.

Like this:

Whereas, to smooth a movement over a fixed period of time, you would typically use an interpolating function like Lerp.

Which method you use is your choice, however, because this particular action (zooming in and out in first-person) is basically a player movement, i.e. raising or lowering a scope to eye level, it doesn’t make sense to smooth the motion by speed.

If the movement was speed based, a greater zoom amount would take longer to transition to than a smaller one.

Instead, for this example, it makes more sense that the transition to the zoomed view takes the same amount of time no matter how far you’re zooming. And for that, you’d normally use Lerp.

However, I don’t want to use Lerp for this either.

While Lerp is great for changing a value over a fixed period of time, it isn’t as convenient for continuous changes, i.e. ‘following’ a value.

Which is what I want the zoom function to do. I want the zoom value to smoothly follow the target amount, but I also want the full motion to take a fixed amount of time.

What I can do, however, is use the Move Towards method but, instead of passing in a fixed speed, I can calculate the amount of angle change required for the full movement and divide that by the duration I want, giving me a speed value.

Like this:

Why do it like this?

Doing it this way means that the speed of the transition is relative to the amount of angle change required. Meaning that the duration of a full zoom movement always remains the same, in this case 1 second. Dividing the result by the duration I want means that I can specify how long the transition should take.

It also means that, if the player releases the zoom button halfway through the transition, the time taken to return to the default field of view will be half, just as you’d expect it to be.

Getting a jerky first-person camera when zoomed in?

Depending on how your character controller is built, you might find that zooming a long way makes the camera less precise than before.

Usually, this is because the amount of rotation applied is magnified with the zoom, and it can often help to reduce look sensitivity while zooming in to help the player aim more easily.

However, there’s also another, less obvious, contributing factor that you might not think to check.

If your character controller’s head rotation is being calculated using Fixed Update, which is used to keep physics-based operations in sync with the physics engine, then all of the player’s movements may be refreshing at a lower rate than the game’s framerate.

For example, when the game is running at 60 fps, Update is being called every 16 ms or thereabouts. The physics engine, however, by default is updated every 20 ms, which works out as 50 frames per second.

So, if the controller’s movement and view rotation are physics-based, that means that most of how the player perceives the game will be at 50 frames per second, no matter how fast it runs.

Which can be particularly noticeable when movements are exaggerated, such as when zooming in.

To fix this, enable Interpolation on the Rigidbody component, which will smooth out the movements between each Fixed Update step.

While zooming based on field of view is a great way to create a realistic zoom effect, it’s best used to emulate real-world lens-based zooming, such as with a scope.

However, that may not be the zoom effect you’re after.

For example, instead of zooming in to view an object that’s far away, it may be that all you really want to do is move the camera closer to the object.

So let’s do that next…

How to zoom an object by moving it closer (the movement method)

Movement-based zoom basically involves moving the camera closer to the object it’s looking at.

Whereas you might use a field of view zoom to look down a weapon’s sights, movement-based zoom is essentially camera control, where the player is simply bringing the camera in closer without changing its viewing angle.

Typically, you might use movement zoom to control a camera’s distance from a player in third-person, or as part of a top-down camera system for a real time strategy game.

How to make a top-down camera

In this example, I’m going to make a simple top-down camera controller that can be panned around with the keyboard and zoomed in using the mouse’s scroll wheel.

This method requires two objects, a parent game object, that will be moved around, and a child object, the camera, which is rotated down towards the scene and will be moved closer to create a basic zoom effect.

Top Down Camera example in Unity

I can move the Camera Controller object around by passing the Horizontal and Vertical axes into the Translate function,

Like this:

This works by getting the movement values from the two directional axes and multiplying them by delta time and a speed value.

In this case, I’ve set the speed value 25, meaning that the camera will move at 25 units per second.

Now that I can move my camera, I want to be able to zoom it in closer to the world.

I can do this by using the local forward direction of the camera object.

Because the camera is rotated down, facing towards the world, moving it along its local forward vector, which is the direction of its blue, Z-Axis, moves it forward in the direction it’s facing.

In this case, that’s towards the world, creating a zooming motion.

Floating camera example unity

The camera is already facing the world, all I need to do to zoom it in is move it forward.

Here’s how it works.

The camera’s forward vector is a direction vector, meaning that its magnitude (the length of the vector) is limited to 1.

So, multiplying its forward direction vector by a float value, such as a zoom amount, for example, will return a new vector, that’s set forward by a number of units, and that can be used to set the camera’s zoomed position.

Like this:

This allows me to set the zoom position of the camera with a single float variable, which makes it easy to manage and easy to control.

For example, if I want to set a maximum zoom amount, I can clamp the zoom value before moving the camera.

Like this:

Or if I want to smoothly move the camera towards its target, I can have the camera follow the zoom value at a set speed using Move Towards.

Like this:

While I now have a method of using the zoom value, a way to limit it to a minimum and maximum zoom level and a way to smoothly move the camera into its zoom position at a set speed,

I still haven’t connected any of it to any kind of control…

How to zoom a camera using the mouse scroll wheel

In this example, I’m making a top-down camera that can be panned around with the keyboard and zoomed in and out using the mouse.

But, I haven’t connected the mouse’s scroll wheel input to the script yet.

Luckily, however, it’s simple to do.

Using the Input Class, Unity’s default method of getting input from devices, I can access the Mouse Scroll Delta, which is a Vector 2 value that returns the vertical and horizontal scroll amounts as values between -1 and 1.

In this case, I only want to detect vertical scroll data, which is the Y value of the Vector 2 value.

I can then use the delta value to increase or decrease the zoom amount.

Like this:

Adding a sensitivity modifier allows me to modify how much the value reacts to the movements of the mouse’s scroll wheel.

This can be useful for tweaking the zoom behaviour, for example, to make zooming over large distances easier, or to allow for differences between scroll wheel inputs.

The result is a smooth position based zoom function, clamped to a minimum and maximum distance, with tweakable sensitivity.

Here’s the complete example:

Movement-based zoom is a great way to add this particular type of zoom control to a game.

There’s just one problem…

Because this method of zooming is essentially a movement control, not a camera control, the camera object can easily be zoomed through other objects, clipping them against the camera.

Geometry clipping against the near plane of the camera

I zoomed in too far…

Depending on your game world, and how high the camera is above that game world, this may not be an issue for you.

However, if the height of your scene varies enough that it’s possible for the camera to move into objects while zooming, you may want to build in some basic collision detection to move the camera back out if it’s too close.

How to automatically zoom the camera out to avoid collisions with objects

One method for detecting collisions against world geometry when using a movement-based camera zoom such as this is to check what’s in the line of sight of the camera with a Ray.

Like this:

Calling this function before calculating the position of the camera will help to prevent it from moving through objects when zoomed in.

This works by firing a ray from the parent object of the camera, covering its entire line of sight. Then, if the ray hits any Colliders in the game world, and if the camera is within 3 units of where it hit, it pulls the zoom level back by 3 units to make space.

This helps to dynamically clamp the maximum zoom level to 3 units in front of any object with a collider attached to it.

Also, because the line of sight is drawn from the camera’s parent object, and not the camera itself, there’s less chance of the camera sneaking in under an object.

Lastly, you may have noticed that I used Spherecast, not Raycast to check for collisions in the camera’s line of sight. Spherecast works like a thick Raycast, essentially firing a sphere into the scene instead of a line, in this case with a radius of 3. In this example, it works well because it basically makes the line wider, allowing it to catch smaller objects more easily.

How to zoom a 2D camera (orthographic zoom)

While zooming with a 3D perspective camera typically involves changing the camera’s field of view, or by simply moving the camera closer to its subject, zooming in and out in 2D works in a different way.

This is because a 2D camera typically uses orthographic projection, not perspective projection, meaning that the 3D world is viewed flat, in 2D.

Orthographic vs Perspective camera projection in Unity

You can see the difference between these two methods by looking at their viewing frustums, which is the region of space in the 3D world that is visible from the camera.

Perspective camera viewing frustum

A perspective camera’s frustum extends out. The far clipping plane is wider than the near clipping plane.

Orthographic viewing frustum

Using an orthographic projection method, the viewing frustum runs along parallel lines. You can see just as much at the far clipping plane as you can at the near clipping plane. Flattening the projection.

Perspective camera projection creates a standard 3D image with visible depth. Objects that are the same size appear smaller when further away and the angle from which they’re viewed is affected by the camera’s relative position.

Perspective camer projection in Unity

A 3D perspective projection camera view

Orthographic camera projection, however, renders the entire image at the same scale, regardless of an object’s distance from the camera.

As such, it’s a commonly used camera mode for 2D games, as it basically renders the scene without any depth.

For example, rendering the same camera angle with an orthographic camera creates an isometric 2D view:

Isometric Game World

Everything looks good in isometric.

Put simply, this means that field of view doesn’t apply when using a 2D camera and that moving the camera closer to an object doesn’t change its size on the screen.

So how can you zoom a 2D camera?

How to zoom in 2D (using an orthographic size)

While a perspective camera can be zoomed by using its field of view, a 2D orthographic camera zoom can be changed using its Size property:

The orthographic size represents half of the vertical viewing volume of the camera in units, while the horizontal size is determined by the screen’s aspect ratio.

Orthographic Size Unity

Orthographic Size in Unity is measured as half of the height of the viewing volume, in units.

This means that to zoom the camera out and show more of the world, you’ll need to increase the orthographic size. While reducing the size of the volume gives the effect of zooming the camera in.

Just like the other methods in this article, zooming with an orthographic camera basically involves setting a single zoom value and having the camera follow it to create a smoothed zooming motion.

Like before, I can use the Move Towards function to follow the zoom target at a set speed, and use minimum and maximum zoom values to keep the camera within a workable range.

Like this:

Just like in the movement-based example, I’ve added a variable to adjust the sensitivity of the scroll wheel, and a speed value to control how fast the camera can zoom in and out.

One key difference, however, between this method and the movement-based zoom method is that, because a larger orthographic size represents a larger viewing area (i.e. zoomed out), you’ll typically want to subtract the value of the scroll wheel delta instead of adding to it. So that scrolling up zooms in and scrolling down zooms out.

Now it’s your turn

Now I want to hear from you.

How are you using camera zoom in your game? Are you using one of the three methods in this article, or something else entirely And what have you learned about zooming the camera that others will find useful?

Whatever it is, let me know below by leaving a comment.

by John Leonard French

Game audio professional and a keen amateur developer.

Get Game Development Tips, Straight to Your inbox

Get helpful tips & tricks and master game development basics the easy way, with deep-dive tutorials and guides.

My favourite time-saving Unity assets

Rewired (the best input management system)

Rewired is an input management asset that extends Unity’s default input system, the Input Manager, adding much needed improvements and support for modern devices. Put simply, it’s much more advanced than the default Input Manager and more reliable than Unity’s new Input System. When I tested both systems, I found Rewired to be surprisingly easy to use and fully featured, so I can understand why everyone loves it.

DOTween Pro (should be built into Unity)

An asset so useful, it should already be built into Unity. Except it’s not. DOTween Pro is an animation and timing tool that allows you to animate anything in Unity. You can move, fade, scale, rotate without writing Coroutines or Lerp functions.

Easy Save (there’s no reason not to use it)

Easy Save makes managing game saves and file serialization extremely easy in Unity. So much so that, for the time it would take to build a save system, vs the cost of buying Easy Save, I don’t recommend making your own save system since Easy Save already exists.

Comments

I’m using the FOV method to create a zooming mechanic for my game. But I’ve run into an issue.

When the FOV is at a value lower than 25, it causes a raycast I’m using to interact with objects, to keep hitting the last spot it hit.

E.g I shoot the raycast at a cube then shoot the raycast at a wall and it still hits the cube. The debug.drawray I’m using shows the ray hitting the wall too. But if I zoom out (increase the FOV) then now I can move from the cube to the wall.

I have no idea what’s happening here. Any ideas?

Does the Raycast start from a position that could be affected by the FOV change? So, for example, are you generating it from the object, or from a screen position? If you’re able to, email me at [email protected] with some more information and I’ll try to help.

i can’t input the fieldOfView from camera, what “using” do you use. sorry im new on unity

You’ll need a reference to a camera, either one that you declare yourself or the main camera (Camera.main) which is the first active object in the scene tagged as main camera. You shouldn’t need additional using directives for that. If I’ve misunderstood, email me at [email protected] and I’ll try to help.

Leave a Comment Cancel reply

Welcome to my blog

John Leonard French - Photo

I’m John, a professional game composer and audio designer. I’m also a keen amateur developer and love learning how to make games. More about me

Latest Posts
  • Godot vs Unity (for making your first game)
  • How to capture the screen in Unity (3 methods)
  • How to write a game design document (with examples)
  • How to start making a game (a guide to planning your first project)
  • How to use script composition in Unity
Thanks for Your Support

Some of my posts include affiliate links, meaning I may earn a commission on purchases you make, at no cost to you, which supports my blog.

2d на Unity3d

В свое время, в начале разработки двухмерной игры на Unity3d, мне пришлось перерыть кучу документации, сайтов, проштудировать answers.unity3d.com и forum.unity3d.com на тему: как сделать 2d-игру на этом 3d-движке. Самыми первыми вопросами были: как правильно настроить камеру, как сделать 2d-спрайт так, чтобы он отображал текстуру «пиксель в пиксель». На то время уже существовал SpriteManager (далее – SM) и даже SM2 с его мощной поддержкой редактора. Судьба сложилась так, что я не мог его тогда купить, да и пробной версии не было. В итоге, мне пришлось самому написать несколько полезных скриптов для реализации 2d на Unity3d. О том, как это сделать, пойдет речь в этой статье.

»

Источники информации

    – официальный сайт движка. Здесь полезными будут странички:

      – официальное руководство пользователя. Начинать изучать здесь.
    • Unity Reference Manual – более углубленное изучение.
    • Scripting Reference – здесь все по библиотеке Unity3d для всех трех поддерживаемых языков (Boo, JavaScript и C#).
    • Unity Resources – здесь можно найти видео-руководства, примеры, презентации.
    • Unity Answers – здесь ответят на ваши вопросы, либо можно найти готовый ответ. Часто пользовался этим ресурсом.
    • Unity Community — форум.

    Что понадобится

    Версия используемого движка – 3.3, весь код написан на C# и будет работать на всех лицензиях Unity. Достаточно скачать бесплатную версию Unity. В комплекте идет MonoDevelop – бесплатная среда для разработки на .NET (на случай, если у вас нет Visual Studio). Среда легко настраивается «под себя», в ней есть все, что необходимо для разработки, поддерживает такие удобные функции, как автодополнение, шаблоны подстановки кода и многое другое. Сам я пользуюсь Visual Studio в связке с Resharper – так удобнее. Редактор Unity поддерживает обе среды.

    Условия использования кода

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

    Условие только одно: при использовании кода (в том числе модифицированного) в коммерческом проекте необходимо указать ссылку на автора (т.е. fischer — меня).

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

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

    Для начала создайте пустую сцену без объектов. Удалите объект MainCamera, добавленный по умолчанию.

    1. Создать пустой объект (GameObject -> Create Empty).
    2. Выбрать его и добавить ему компонент Camera (Component -> Rendering -> Camera).

    Для 2d-графики положение спрайтов в пространстве не важно. На много важнее, как спрайты друг друга перекрывают. Камера поддерживает два режима (вида проекции): перспективный (Perspective) и ортогональный (Orthographic). Первый используется во всех 3d-играх: объекты, расположенные дальше от камеры, выглядят меньше. Это почти то, как мы видим наш мир. Нам нужен второй режим, Orthographic – объекты всегда рисуются реального размера и перекрывают друг друга в зависимости от расстояния до камеры. Идеальный режим камеры для 2d и изометрии. В окне Inspector в компоненте Camera вновь созданного объекта в поле Projection выберите Orthographic. При этом некоторые параметры (соответствующие Perspective-режиму) пропадут, но появится параметр Size – размер ортогональной камеры.

    Теперь настроим камеру так, чтобы каждый пиксель на экране соответствовал одной единице (unit) пространства в Unity. В дальнейшем это будет удобно при перемещении спрайтов и задании их размеров в пикселях. Для этого размер ортогональной камеры (параметр Size) должен равняться половине высоты экрана в пикселях. Например, если это экран iPhone 3G в портретном режиме, разрешение экрана которого 320×480, то Size = h/2 = 480/2 = 240.

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

    1. Автоматически этому объекту добавится компонент Camera. За это отвечает атрибут RequireComponent.
    2. Выполнится функция Awake. За это отвечает атрибут ExecuteInEditMode, который заставляет выполняться скрипты прямо в редакторе.
    3. В результате вызова этой функции камера станет ортогональной.
    4. Ее размер будет установлен таким, чтобы один пиксель на экране соответствовал одной единице Unity (вызов функции SetUniform). Это будет выполняться автоматически для любого экрана.

    Улучшения
    1. Если размер экрана может меняться во время выполнения (поворот экрана смартфона, смена разрешения пользователем), неплохо бы автоматически менять размер камеры. Это можно делать в функции LateUpdate.
    2. Если освещение использоваться не будет (как и бывает в большинстве 2d-игр), рекомендую в настройках проекта (File->Build Settings->Player Settings->Other Settings) установить параметр Rendering Path в значение Vertex Lit. Это самый простой способ отрисовки объектов (каждый объект за один шаг для всех источников света), поддерживаемый большинством устройств. В моем случае для iOS-устройств это дало скачок в производительности. То же самое можно сделать для конкретной камеры. По умолчанию камера используют значение из Player Settings.

    Спрайт

    Спрайт — прямоугольник с наложенной на него текстурой. Договоримся, что он по умолчанию будет расположен в плоскости XOY. Тогда за взаимное расположение спрайтов (слои) будет отвечать координата Z.

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

    Спрайт будет задаваться несколькими параметрами:

      zero – положение нулевой точки спрайта относительно его нижнего левого угла. Измеряется в долях спрайта, т.е. (0.5, 0.5) – это центр спрайта. Нужен для правильного смещения спрайта в не зависимости от того, как он расположен на текстуре.
      Подсказка: чтобы в редакторе увидеть на спрайте оси поворота/перемещения именно в нулевой точке, а не в центре (по умолчанию), необходимо на элементе управления Transform Gizmo Toggles панели инструментов выбрать Pivot.

    1. списком вершин,
    2. списком индексов вершин, составляющих вершины треугольников, из которых состоит прямоугольник,
    3. списком соответствующих вершинам текстурных координат.

    Чтобы нарисовать меш, понадобятся компоненты MeshRenderer и MeshFilter. Первый компонент содержит ссылки на материалы текстур для спрайта. Второй из них содержит объект MeshFilter.mesh, который он и рисует. Для изменения спрайта нужно, соответственно, изменять этот объект. Сам спрайт реализуется через компонент SampleSprite. Для того чтобы у спрайта эти два компонента были всегда, добавим ему соответствующие атрибуты RequireComponent:

    Атрибут AddComponentMenu добавляет в меню Component редактора пункт Sprites->Sample Sprite. Используя его можно добавить к любому объекту Unity наш компонент SampleSprite.

    Для того чтобы можно было видеть спрайт во время редактирования, атрибут ExecuteInEditMode позволяет вызывать функции Awake и Start класса SampleSprite прямо в редакторе. Внутри этих функций создается меш:

    При инициализации меша нужно учитывать флаг pixelCorrect. Проверяем, во сколько раз высота экрана отличается от размера камеры — во столько раз нужно увеличить меш, учитывая, что при нормальном варианте (высота экрана равна удвоенному размеру ортогональной камеры) размер меша равен размеру области текстуры для спрайта:

    NonNormalizedTextureCoords – текстурные координаты в пикселях. Определяются через нормализованные текстурные координаты (параметр спрайта) и размер самой текстуры TextureSize:

    Заметьте, что меш инициализируется в функции Start, потому что при его инициализации используется информация из камеры, а она инициализируется нами в Awake, т.е. в Start такая информация уже доступна для других объектов (в Unity сначала вызываются все Awake, затем все Start, но порядок вызова одной и той же функции для различных объектов не определён). Так же в этом примере используется Camera.main — главная камера на сцене. Т.е. наша камера должна быть помечена тегом MainCamera.

    В принципе, на этом этапе со спрайтом уже можно работать. Для этого к любому объекту нужно прикрепить компонент SampleSprite (например, через меню Component или перетянув на него файл скрипта). Автоматически к нему добавятся компоненты MeshFilter и MeshRenderer. Теперь если перетянуть на этот объект материал текстуры (или текстуру, а материал создастся автоматически), и настроить параметры, то можно будет увидеть готовое 2d-изображение.

    Настройка параметров текстуры
    1. чтобы движение спрайта было плавным, чтобы при изменении размеров спрайт выглядел сглаженным, необходимо параметр экспорта текстуры Filter Mode установить в Bilinear или Trilinear);
    2. установите Texture Type в значение GUI;
    3. не забудьте убрать компрессию, установив значение параметра Format в Truecolor.
    Освещение
    1. В версии 3.3 есть группа шейдеров Unlit с отключенным освещением. Для спрайтов с прозрачностью подойдет шейдер Unlit->Transparent, для заднего фона Unlit->Texture.
    2. В старых версиях Unity можно использовать шейдер Transparent->Diffuse. Но тогда надо не забыть в Edit->Render Settings проставить Ambient Light в белый, чтобы все спрайты были натурального цвета. Иначе они будут затемненными, потому что по умолчанию в качестве Ambient Light стоит оттенок серого.
    3. Можно написать свой шейдер, в котором освещение будет отключено. О том, как это сделать, можно посмотреть в официальном пособии по шейдерам Unity.

    Использование возможностей редактора

    1. Тег EditorOnly.
    2. Создание редакторов игровых объектов в Инспекторе Компонентов путем наследования от класса Editor.
    3. Создание окон редактора путем наследования от класса EditorWindow.

    Внимание: все скрипты, связанные с редактором, должны располагаться в папке Assets/Editor.

    Атрибут CustomEditor говорит о том, что данный класс будет использован в Инспекторе Компонентов как редактор для класса-компонента SampleSprite. Свойство Target введено для удобства обращения к полям редактируемого объекта, т.к. выдаваемый по умолчанию объект target имеет тип Object. В переопределенной функции OnInspectorGUI задается список параметров компонента SampleSprite, отображаемых в Инспекторе. Если хоть один из этих параметров изменится (GUI.changed), спрайт обновится, и мы увидим результат изменения на экране, а также сохранятся измененные параметры спрайта (EditorUtility.SetDirty).

    Редактируемые параметры добавим в класс SampleSprite и сделаем их условно-компилируемыми (чтобы этот код не попал в конечный продукт, а работал только в редакторе):

    В данном случае параметр Zero измеряется в тех же единицах, что и size, а TextureCoords – в пикселях текстуры.

    Оптимизация, улучшения и прочее

    Уменьшение числа Draw Calls
    1. Static batching. Если объект никогда не изменяется, то его можно пометить как статический (галочка Static в Инспекторе). Все такие объекты будут объединены в один большой и будут рисоваться за один Draw Call. К сожалению, функция static batching доступна только в Pro-версии Unity.
    2. Dynamic batching. Если несколько объектов используют один и тот же материал, Unity перед отрисовкой объединяет их в один, и все они будут рисоваться за один Draw Call. Для достижения этого эффекта текстуры необходимо объединять в атлас – одну большую текстуру. Используйте атласы – они позволяют сократить как количество Draw Call (за счет dynamic batching), так и объем памяти, занимаемой текстурами (что очень актуально для мобильных платформ).
      Подсказка: включение/отключение видов batching для некоторых платформ осуществляется в File->Build Settings->Player Settings.
    3. Менеджер спрайтов. Одна из реализаций – SpriteManager. Спрайт добавляется в менеджер спрайтов, который использует одну текстуру-атлас (в компоненте MeshRenderer), и создает для спрайтов меш (в компоненте MeshFilter), состоящий из множества прямоугольников, по одному для каждого спрайта (к этой реализации автор прикрутил удобство редактора и получил SM2). Также улучшить менеджер спрайтов можно за счет задания спрайту ссылки на используемый материал, все материалы хранить в компоненте MeshRenderer менеджера спрайтов, а меш рисовать как совокупность более маленьких мешей (по одному на материал), пользуясь возможностями Mesh.CombineMeshes, Mesh.SetTriangles, Mesh.GetTriangles, Mesh.subMeshCount. Это позволит не заводить для каждого материала по менеджеру спрайтов.
    Некоторые улучшения кода
    1. Конечно, лучше избавится от постоянного вызова функции CreateMesh, который приводит к созданию нового меша (в данном случае это несущественно, т.к. все происходит в редакторе, а в реальном приложении спрайт будет создаваться один раз и больше не будет меняться). Вместо этого достаточно изменять параметры Mesh.vertices, Mesh.uv, Mesh.triangles. Не забывайте вызвать mesh.RecalculateBounds(), если был изменен массив вершин vertices. Если же изменен массив triangles, то эта функция вызовется автоматически.
    2. Вместо Camera.main лучше задавать камеру как параметр скрипта.
    Как делать анимации

    Как делать полноценные спрайтовые анимации можно посмотреть на примере SpriteManager.
    В нашей игре Papa Penguin спрайтовых анимаций не было. Вместо этого, например, пингвин скреплялся из частей по нулевым точкам спрайтов, а движение этих частей осуществлялось с помощью компонента Animation. Этого вполне хватило. В Unity это очень мощный инструмент. В анимацию, например, можно вставлять даже вызовы функций из скриптов.

    2d-физика
    1. Сделать объект триггером (флажок Is Trigger).
    2. Позволить объекту подвергаться физическим воздействиям. Для этого к объекту можно дополнительно прикрепить компонент Component->Physics->Rigidbody.

    Физика Unity3d предлагает также другие богатые возможности: силы, приложенные к определенным точкам объекта, гравитация, точки соединения (Fixed Joint, Spring Joint). Используя все это, можно создать неплохую игру, основанную на физике.

    Альтернативы

      – простая платная система для создания 2d-анимаций в Unity (на момент написания статьи плагин стоил $35). – система классов для создания спрайтовых анимаций. Поддерживает отрисовку спрайтов за один Draw Call, менеджер спрайтов, анимации и атласы. Довольно неудобен в настройке, но если бюджет ограничен, вполне пригоден для использования. (Sprite Manager 2) – платный менеджер спрайтов с поддержкой редактора. Поддерживает множество полезных функций в дополнение к бесплатной версии: создание атласов, использование возможностей редактора для выделения области текстуры, автоматического создания анимаций и многое другое. Если не хочется реализовывать спрайты вручную, то SM2, на мой взгляд – самый лучший выбор. Стоит $150 с 60-дневной возможностью вернуть деньги назад, если не понравится. , $50. Этот плагин не совсем спрайтовый, а скорее векторный. Плагин обладает множеством интересных возможностей:

      • создание 2d-мешей и линий на основе кривых Безье;
      • контуры объектов различной ширины;
      • заливка одним цветом/градиент;
      • текстурированные объекты;
      • и многое другое.

    Заключение

    Всего того, о чем я написал, вполне хватит для написания своей 2d-системы и последующего ее использования при создании двухмерной игры. Трехмерность движка и поддержка физики предлагает нам новые богатые возможности, а высокая скорость разработки на Unity (что является большим плюсом движка) позволит сократить затраты.

    Навигация в окне сцены

    Окно сцены имеет несколько способов навигации для ускорения работы.

    Содержание

    Перемещение стрелками

    Вы можете использовать клавиши стрелок для перемещения в сцене — «прогулки» по ней. Стрелки вверх и вниз двигают камеру вперед и назад. Стрелки налево и направо панорамируют вид в стороны. Удерживая при этом клавишу Shift Вы будете двигаться быстрее.

    Фокусирование

    Если Вы выберете объект в Иерархии и нажмете клавишу F,- вид будет перемещен для центрирования выбранного объекта. Эта функция называется «рамка выбора».

    Перемещение, Вращение и Зум

    Эти операции ключевые в навигации по сцене, так что Юнити предоставляет несколько разных путей их выполнения для максимального удобства

    Использование инструмента Рука

    Когда выбран инструмент Рука (быстрая клавиша Q), доступны следующее управление мышью:

    SceneView40-1.jpg

    Перемещение: щелчок-перетаскивание для перемещения сцены вокруг камеры.

    SceneView40-2.jpg

    Вращение: удерживайте Alt и сделайте щелчок-перетаскивание для перемещения камеры вокруг текущей точки опоры.

    SceneView40-3.jpg

    Масштабирование: удерживайте Control (Command на Mac) щелчок-перетаскивание для масштабирования сцены.Удерживание Shift будет увеличивать скорость перемещений и масштабирования.

    Быстрые клавиши без использования инструмента Рука

    Для большей эффективности все эти способы могут быть использованы не зависимо от того какой инструмент трансформации выбран. Удобство управления зависит от того что Вы используете — мышь или трекбол:

    Удерживаем Alt-Command и щелкнув тащим.

    Режим пролета

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

    • Щелкните и удерживайте правую кнопку мыши.
    • Теперь Вы можете двигаться используя мышь и клавиши WASD для перемещения налево/направо вперед/назад и клавиши Q и E для смещения вверх/вниз.
    • При удерживании Shift Вы будете двигаться быстрее.

    Режим пролета разработан для вида перспективы. В виде Изометрии вместо режима пролета будет производиться вращение камеры.

    Гизмо сцены

    В верхнем правом углу Окна сцены выводится Гизмо сцены. Он отображает текущую ориентацию камеры и позволяет Вам быстро модифицировать угол обзора.

    SceneView40-4.jpg

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

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

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