banner



How To Make Top Down Camera Follow Character Unity

For a developer, the camera is one of the cornerstones of the game evolution procedure. From just showing your game view in a chess app to masterfully directing camera movement in a 3D AAA game to obtain cinematic effects, cameras are basically used in any video game e'er fabricated, even earlier actually being chosen "cameras".

In this article I'm going to explain how to pattern a camera arrangement for 2nd games, and I'grand also going to explain some points on how to go about implementing it in i of the about popular game engines out in that location, Unity.

From 2D to two.5D: An Extensible Camera Arrangement

The camera arrangement nosotros are going to design together is modular and extensible. It has a basic core consisting of several components which will ensure the basic functionality, so various components/effects that can exist optionally used, depending on the state of affairs at hand.

The camera organization nosotros are building here is targeted at 2nd platform games, but tin easily extended to other types of second games, 2.5D games or even 3D games.

Mastering 2d Camera in Unity: A Tutorial for Game Developers

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

Tracking

Most of the camera movement we'll do hither will be based on tracking. That is the ability of an object, in this case the camera, to track other objects as they move about in the game scene. The types of tracking that nosotros'll exist implementing are going to solve some common scenarios encountered in 2d platform games, but they can be extended with new types of tracking for other detail scenarios you might have.

Effects

Nosotros will be implementing some cool furnishings like camera shake, camera zoom, camera fade, and colour overlay.

Getting Started

Create a new 2D project in Unity and import standard assets, peculiarly the RobotBoy character. Adjacent, create a ground box and add a character instance. You should be able to walk and jump with your character in your current scene. Make sure the camera is set to Orthographic mode (it is fix to Perspective by default).

Tracking a Target

The following script volition add basic tracking behavior to our main photographic camera. The script must be attached as a component to the main photographic camera in your scene and it exposes a field for assigning a target object to track. And so the script ensures the x and y coordinates of the camera are the same with the object information technology tracks. All this processing is done during the Update footstep.

          [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 hierarchy over the "Tracking Target" field exposed past our following behavior in gild to enable tracking of the main character.

Calculation Outset

All proficient, but we tin can see a limitation directly off the bat: the grapheme is ever in the middle of our scene. We can come across a lot backside the character, which is normally stuff we are not interested in, and nosotros are seeing too little of what is ahead of our graphic symbol, which might be detrimental to the gameplay.

To solve this, we are adding some new fields to the script that will allow the positioning of the camera at an offset from its target.

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

Beneath you tin see a possible configuration for the two new fields:

Smoothing Things Out

The camera motion is pretty strong and volition also produce dizziness in some players from the constant perceived movement of the environment. In order to set this nosotros'll exist adding some delay in camera tracking using linear interpolation, and a new field to control how fast the photographic camera gets into place later on the graphic symbol starts changing its position.

          [SerializeField] protected float followSpeed;  // ...  protected override void Update() {     float xTarget = trackingTarget.position.10 + xOffset;     bladder yTarget = trackingTarget.position.y + yOffset;      bladder xNew = Mathf.Lerp(transform.position.ten, 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: Centrality Locking

Since it is not pleasant for your brain to watch the camera going up and down all the fourth dimension along with the character, we are introducing axis locking. This means we can limit the tracking to only one axis. Then nosotros'll separate our tracking code into axis contained tracking, and we'll take the new locking flags into account.

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

Lane System

Now that the camera only tracks the player horizontally, nosotros are limited to the height of one screen. If the character 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 post-obit scenario:

The character is initially on the lower lane. While the grapheme remains inside the boundaries of this lane the camera will be moving only horizontally on lane specific height offset nosotros can set.

Every bit soon equally the graphic symbol enters another lane, the camera will transition to that lane and continue to motility horizontally from there on until the next lane change occurs.

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

Lanes' levels can change throughout the game level based on the designer'southward specific needs, or tin can be interrupted altogether and another camera tracking system can take their place. Therefore, nosotros need some limiters for specifying lane zones.

Implementation

A possible implementation is to add lanes every bit uncomplicated objects in the scene. We volition use their Y position coordinate paired with Y offset in the tracking script higher up to implement the organisation. Therefore, their positioning on the X and Z coordinates does not matter.

Add together the LaneSystem class to camera, along with the tracking class, and assign the lane objects to the provided assortment. Also assign the player character to the Reference field. As the reference is positioned between a lane and another lane, the lower 1 of the ii will be used to position the camera.

And the LaneSystem form takes care of moving the camera betwixt lanes, based on reference position. The followSpeed is used here once more for position interpolation, to forbid lane switching from being too abrupt:

          [SerializeField] Transform reference;  [SerializeField] List<Transform> lanes;  [SerializeField] float followSpeed = 5f;  // ...  void Update() { 	 bladder targetYCoord = transform.position.y; 	 if (lanes.Count > i) 	 { 		 int i = 0; 		 for (i = 0; i < lanes.Count - 1; ++i) 		 { 			 if ((reference.position.y > lanes[i].position.y) && 				 (reference.position.y <= lanes[i + i].position.y)) 			 { 				 targetYCoord = lanes[i].position.y; 				 intermission; 			 } 		 }  		 if (i == lanes.Count - 1)  			 targetYCoord = lanes[lanes.Count - ane].position.y; 	 } 	 else 	 { 		 targetYCoord = lanes[0].position.y; 	 } 	 float 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 ane, and is left as such every bit an exercise for the reader.

Lock Node System

Having the camera motility on lanes is great, simply sometimes we need the camera to be locked on to something, a point of interest (POI) in the game scene.

This can be achieved past configuring such POI in the scene and attaching a trigger collider to them. Whenever the graphic symbol enters that trigger collider, we move the camera and stay on the POI. Equally the character moves and so leaves the POI's trigger collider, we get back to some other type of tracking, usually the standard follow behavior.

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

Implementation

In order to configure a lock node, just create an object (can be empty or similar in the screenshot below, a sprite) and attach a large Circle Collider 2D component to it so it marks the area the player will be in when the photographic camera will focus the node. You tin cull any blazon of collider, I'k choosing Circle as an example here. As well create a tag you lot tin easily check for, like "CameraNode" and assign it to this object.

Add the post-obit property to the tracking script on your camera:

          public Transform TrackingTarget {     become     {         return trackingTarget;     }     set     {         trackingTarget = value;     } }                  

And so attach the post-obit script to the player, that volition allow information technology to temporarily switch the photographic camera's target to the lock node you've prepare. The script will also call back its previous target then information technology can get dorsum to it when the player is out of the trigger area. You tin go ahead and transform this in a total stack if you need that, simply for our purpose since nosotros don't overlap multiple lock nodes this will practice. Also please be aware that you can tweak the position of the Circle Collider second, or once more add whatever other kind of collider to trigger the camera lock, this is just a mere example.

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

0 Response to "How To Make Top Down Camera Follow Character Unity"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel