banner



How To Make The Camera Move Freely In Unity

For a developer, the camera is one of the cornerstones of the game development procedure. From just showing your game view in a chess app to masterfully directing camera motility in a 3D AAA game to obtain cinematic furnishings, cameras are basically used in whatever video game always made, even before really being called "cameras".

In this commodity I'grand going to explain how to blueprint a camera system for 2nd games, and I'm also going to explain some points on how to go about implementing it in 1 of the most popular game engines out there, Unity.

From second to two.5D: An Extensible Camera System

The camera system we are going to blueprint together is modular and extensible. It has a basic cadre consisting of several components which will ensure the bones functionality, and so various components/furnishings that can be optionally used, depending on the situation at hand.

The camera arrangement nosotros are building here is targeted at 2nd platform games, but can easily extended to other types of second games, 2.5D games or fifty-fifty 3D games.

Mastering second Camera in Unity: A Tutorial for Game Developers

I am going to split the camera functionality into two principal groups: camera tracking and photographic camera effects.

Tracking

Nigh of the camera movement we'll do here will be based on tracking. That is the ability of an object, in this case the camera, to track other objects as they motion well-nigh in the game scene. The types of tracking that we'll be implementing are going to solve some common scenarios encountered in 2d platform games, just they can be extended with new types of tracking for other item scenarios you lot might accept.

Effects

We volition be implementing some cool effects like camera shake, camera zoom, camera fade, and color overlay.

Getting Started

Create a new 2D project in Unity and import standard avails, particularly the RobotBoy grapheme. Next, create a ground box and add a character instance. You should be able to walk and jump with your character in your electric current scene. Make sure the camera is ready to Orthographic mode (it is ready to Perspective past default).

Tracking a Target

The post-obit script volition add basic tracking behavior to our primary photographic camera. The script must be attached as a component to the main camera in your scene and it exposes a field for assigning a target object to rails. So the script ensures the x and y coordinates of the photographic camera are the aforementioned with the object it tracks. All this processing is done during the Update step.

          [SerializeField] protected Transform trackingTarget;  // ...  void Update() {     transform.position = new Vector3(trackingTarget.position.x,          trackingTarget.position.y, transform.position.z); }                  

Drag the RobotBoy graphic symbol from your scene bureaucracy over the "Tracking Target" field exposed past our following beliefs in guild to enable tracking of the chief character.

Adding Offset

All good, but we tin see a limitation straight off the bat: the graphic symbol is always in the heart of our scene. We can see a lot behind the character, which is usually stuff we are not interested in, and we are seeing too little of what is ahead of our character, which might be detrimental to the gameplay.

To solve this, we are calculation some new fields to the script that volition let the positioning of the camera at an beginning from its target.

          [SerializeField] float xOffset;  [SerializeField] float yOffset;  // ...  void Update() {     transform.position = new Vector3(trackingTarget.position.x + xOffset,          trackingTarget.position.y + yOffset, transform.position.z); }                  

Below yous tin can see a possible configuration for the ii new fields:

Smoothing Things Out

The camera movement is pretty stiff and volition too produce dizziness in some players from the abiding perceived movement of the surround. In order to fix this we'll be adding some filibuster in camera tracking using linear interpolation, and a new field to control how fast the camera gets into place after the character starts changing its position.

          [SerializeField] protected float followSpeed;  // ...  protected override void Update() {     bladder xTarget = trackingTarget.position.ten + xOffset;     bladder yTarget = trackingTarget.position.y + yOffset;      bladder xNew = Mathf.Lerp(transform.position.10, xTarget, Time.deltaTime * followSpeed);     float yNew = Mathf.Lerp(transform.position.y, yTarget, Time.deltaTime * followSpeed);      transform.position = new Vector3(xNew, yNew, transform.position.z); }                  

Stop the Dizziness: Axis Locking

Since it is non pleasant for your brain to lookout the camera going up and down all the time along with the character, we are introducing centrality locking. This ways nosotros can limit the tracking to only i axis. And so we'll divide our tracking code into axis independent tracking, and we'll take the new locking flags into account.

          [SerializeField] protected bool isXLocked = false;  [SerializeField] protected bool isYLocked = false;  // ...  float xNew = transform.position.x; if (!isXLocked) {     xNew = Mathf.Lerp(transform.position.x, xTarget, Time.deltaTime * followSpeed); }  bladder yNew = transform.position.y; if (!isYLocked) {      yNew = Mathf.Lerp(transform.position.y, yTarget, Time.deltaTime * followSpeed); }                  

Lane Arrangement

Now that the camera only tracks the player horizontally, nosotros are limited to the height of 1 screen. If the graphic symbol climbs some ladder or jumps higher than this, nosotros have to follow. The way we are doing this is by using a lane system.

Imagine the following scenario:

The character is initially on the lower lane. While the character remains within the boundaries of this lane the camera will be moving only horizontally on lane specific height kickoff nosotros tin can gear up.

Every bit before long as the graphic symbol enters another lane, the camera will transition to that lane and continue to move horizontally from there on until the next lane change occurs.

Care must exist taken on lane design in order to prevent fast lane switching during deportment like jumps, which can create confusion for the player. A lane should be changed only if the role player'south grapheme is going to stay on it for a while.

Lanes' levels tin change throughout the game level based on the designer's specific needs, or can exist interrupted altogether and some other camera tracking organization can take their identify. Therefore, we need some limiters for specifying lane zones.

Implementation

A possible implementation is to add lanes every bit simple objects in the scene. Nosotros will utilise their Y position coordinate paired with Y offset in the tracking script to a higher place to implement the system. Therefore, their positioning on the X and Z coordinates does not matter.

Add together the LaneSystem form to camera, forth with the tracking class, and assign the lane objects to the provided array. Also assign the player character to the Reference field. As the reference is positioned between a lane and another lane, the lower i of the 2 volition be used to position the camera.

And the LaneSystem class takes care of moving the camera between lanes, based on reference position. The followSpeed is used here once again for position interpolation, to preclude lane switching from existence too abrupt:

          [SerializeField] Transform reference;  [SerializeField] List<Transform> lanes;  [SerializeField] float followSpeed = 5f;  // ...  void Update() { 	 float targetYCoord = transform.position.y; 	 if (lanes.Count > 1) 	 { 		 int i = 0; 		 for (i = 0; i < lanes.Count - 1; ++i) 		 { 			 if ((reference.position.y > lanes[i].position.y) && 				 (reference.position.y <= lanes[i + one].position.y)) 			 { 				 targetYCoord = lanes[i].position.y; 				 break; 			 } 		 }  		 if (i == lanes.Count - 1)  			 targetYCoord = lanes[lanes.Count - ane].position.y; 	 } 	 else 	 { 		 targetYCoord = lanes[0].position.y; 	 } 	 bladder yCoord = Mathf.Lerp(transform.position.y, targetYCoord, Time.deltaTime * followSpeed); 	 transform.position = new Vector3(transform.position.x, yCoord, transform.position.z); }                  

This implementation is non a WYSIWYG one, and is left as such as an practice for the reader.

Lock Node Organization

Having the photographic camera movement on lanes is bang-up, but sometimes we need the camera to be locked on to something, a indicate of involvement (POI) in the game scene.

This can be accomplished by configuring such POI in the scene and attaching a trigger collider to them. Whenever the character enters that trigger collider, we move the camera and stay on the POI. As the character moves and then leaves the POI's trigger collider, we get dorsum to another type of tracking, ordinarily the standard follow behavior.

The switching of the photographic camera tracking to a lock node and back can exist done either by a simple switch or by a stack system, on which tracking modes are pushed and popped.

Implementation

In society to configure a lock node, merely create an object (tin be empty or like in the screenshot below, a sprite) and attach a big Circumvolve Collider 2D component to it so information technology marks the area the player volition be in when the camera will focus the node. You tin choose any type of collider, I'yard choosing Circle every bit an example here. Also create a tag you can easily check for, like "CameraNode" and assign information technology to this object.

Add together the post-obit holding to the tracking script on your photographic camera:

          public Transform TrackingTarget {     get     {         return trackingTarget;     }     fix     {         trackingTarget = value;     } }                  

Then attach the following script to the role player, that will allow it to temporarily switch the photographic camera's target to the lock node you've set. The script will also call up its previous target and so it can get dorsum to information technology when the player is out of the trigger area. You tin go alee and transform this in a full stack if yous need that, simply for our purpose since we don't overlap multiple lock nodes this will do. Also please be enlightened that yous can tweak the position of the Circle Collider 2nd, or once again add whatsoever other kind of collider to trigger the camera lock, this is just a mere example.

          public class LockBehavior : MonoBehaviour { 	#region Public Fields  	[SerializeField] 	Photographic camera camera;  	[SerializeField] 	string tag;  	

0 Response to "How To Make The Camera Move Freely In Unity"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel