banner



How To Make The Camera Follow The Player In Unity

So you have a game either in second or 3d which you lot need the camera to follow the player. In this tutorial we volition be discussing the unlike methods how you lot tin can use unity second and how to brand the camera follow the actor in your game. We volition look at bones principles of doing this in unity 2nd.

Then to do this in 3d is very similar, you will merely brand use of the z axis also depending on the view you take in your game.

Whether that be top downwardly, side scrolling or first or third person.

Rather want to watch video, here is the video version of this tutorial.

Beginning nosotros need to setup a very bones unity second project with a player moving in our scene. So I volition setup a square equally our actor moving effectually left, right,up and downwards.

With this we will just add a basic background so we get some depth in our second earth. From at that place we will put together a unity 2d camera movement which will allow for a elevation down thespian camera follow.

We will then go ahead and add some premises to our camera and then we can limit our camera movement.

To commencement we create a new unity 2d project.

Unity 2d how to make camera follow player

We will start off by adding a elementary role player as a square sprite.

Then get alee and correct click in our assets binder and create a square sprite with the below steps in the screenshots.

unity camera follow behind player

Rename our square to player.

unity 2d camera movement

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

unity camera follow player without rotation

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

Once done let's create a actor movement script.

unity 2d platformer movement

Telephone call that player movement.

unity 2d camera bounds

Drag and drop that onto your actor game object similar so.

unity camera follow player 3rd person

Now go ahead and open up the thespian movement script in visual studio. Replace the code in that script with this.

          using Organisation.Collections; using System.Collections.Generic; using UnityEngine;  public class PlayerMovement : MonoBehaviour {     // Start is called before the start frame update     private Rigidbody2D rb;     public float moveSpeed = 100f;     void Start()     {         rb = GetComponent<Rigidbody2D>();     }      // Update is called once per frame     void Update()     {         rb.velocity = Vector2.null;                           if(Input.GetKey(KeyCode.DownArrow)) {             rb.velocity = new Vector2(0, -moveSpeed * Fourth dimension.deltaTime);         }         if (Input.GetKey(KeyCode.RightArrow)) {             rb.velocity = new Vector2(moveSpeed*Time.deltaTime, 0);         }         if (Input.GetKey(KeyCode.UpArrow)) {             rb.velocity = new Vector2(0, moveSpeed * Time.deltaTime);         }         if (Input.GetKey(KeyCode.LeftArrow)) {             rb.velocity = new Vector2(-moveSpeed*Time.deltaTime,0);         }             } }                  

Now y'all should have a moving player when you hit play in unity. Let'southward simply add a basic background. I fabricated this one in inkscape very quickly.

unity camera follow player rotation

Then dragging that into our unity project we now take.

how to make camera follow player position and rotation unity 3d

Simplest player photographic camera follow and move

The simplest style to practise a photographic camera follow is to only child our photographic camera to our player like this.

unity 2d how to make camera follow player background image and parenting camera

Then if you have done this and you take moved your player to the edge of the screen yous have probably figured out that this is not the nigh efficient way.

As your player may be able to go out of the premises of the screen and and so will your camera view. So y'all will end up with something like this.

unity 2d how to make camera follow player camera bounds issue

Then with this method we have very lilliputian control over our photographic camera'southward transform, information technology's all dependent on the player transform.

A better method is for usa to rather use a script.

Unity second thespian follow and camera move script

So go ahead and create a new c# script and telephone call it camera follow similar this.

2d camera
2d camera

Open that up in c# and utilize this script below. I will explain how this works afterwards.

          using System.Collections; using System.Collections.Generic; using UnityEngine;  public form CameraFollow : MonoBehaviour {      public Transform followTransform;           // Update is called once per frame     void FixedUpdate()     {         this.transform.position = new Vector3(followTransform.position.x, followTransform.position.y, this.transform.position.z);                       } }                  

In it'southward nearly basic form this is what you will demand to brand the camera follow your player with a script. So simply put we declare a followTransform, this volition be a our player'southward transform we volition be post-obit with our camera.

Nosotros then in fixedupdate change our camera transform position to that of our actor only on the x and y centrality considering we are moving in 2d space.

Go ahead now save this and add together this to your photographic camera. Similar so:

Besides drag your thespian into the follow transform deadening like above. If you run your actor camera follow projection now your photographic camera should be following your player.

Well this is only half the story. Let us now implement some camera bounds so our role player won't go exterior our groundwork.

Unity 2d photographic camera premises

To create a camera premises yous firstly need to create a way of measuring premises. You can practise 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.

Unity 2d camera bounds adding a boxcollider2d

With the boxcollider2d added we now accept a way of getting the bounds of our background scene. Then let's at present add some c# lawmaking to our camera follow script and brand information technology restrict the bounds on our camera.

          using System.Collections; using System.Collections.Generic; using UnityEngine;  public form CameraFollow : MonoBehaviour {      public Transform followTransform;     public BoxCollider2D mapBounds;      private float xMin, xMax, yMin, yMax;     private float camY,camX;     private float camOrthsize;     private float cameraRatio;     individual Camera mainCam;      private void Get-go()     {         xMin = mapBounds.premises.min.ten;         xMax = mapBounds.bounds.max.ten;         yMin = mapBounds.bounds.min.y;         yMax = mapBounds.bounds.max.y;         mainCam = GetComponent<Camera>();         camOrthsize = mainCam.orthographicSize;         cameraRatio = (xMax + camOrthsize) / 2.0f;     }     // Update is called in one case per frame     void FixedUpdate()     {         camY = Mathf.Clamp(followTransform.position.y, yMin + camOrthsize, yMax - camOrthsize);         camX = Mathf.Clamp(followTransform.position.x, xMin + cameraRatio, xMax - cameraRatio);         this.transform.position = new Vector3(camX, camY, this.transform.position.z);                       } }                  

This may seem very complicated when y'all first look at. Withal it is quite simple. First thing nosotros added to our script is to go our mapBounds which is a boxcollider2d which have declared as public.

We then declare a few bladder variables for our xMin,xMax,yMax,yMin these will agree our min and max bounds from our boxcollider2d. Then we create a camX and camY variable to control our photographic camera movement.

We declare camOrthsize which volition agree our vertical size of our photographic camera field of view. This translates to half of that size in world infinite.

There is too a cameraRatio variable which will determine our horizontal camera ratio or orthographic size.

We finally and then declare a photographic camera variable to concord our master photographic camera.

In the start method we prepare out bounds variables. Nosotros go our camera component to go our main camera.

After this we go the orthographic size of our camera.

Then we calculate the horizontal size based off the one-half size of the camera ortho and add that to the maximum size on the ten of our bounds and simply divide that by 2.

Nosotros now know how far we tin motion on the x centrality before our camera will exit of view. We dissever specifically by two.0f to keep the adding as a bladder value so we don't lose precision.

Finally in our fixedupdate method we clench down our variables and offset them past the half size of our camera ortho past adding and subtracting them to their relevant positions.

You may need to get through this script a few times to full understand. One time you got that downward. Make you lot add your script to your photographic camera in unity.

As well every bit dragged your background into the map bounds slot.

When you run this yous should end upwards with something that functions like this.

Unity 2d camera bounds demonstration

So every bit you see your player volition approach the bounds and the camera will cease post-obit at that signal.

If yous have done all this correctly yous 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 motion

This is really very simple. With what you have here yous will be able to practice this just fine. You may want to simply add some smoothing with your camera movement though.

You tin can exercise this using a lerp part. So here is how we will modify the c# script to make the player camera follow movement polish.

          using System.Collections; using Organisation.Collections.Generic; using UnityEngine;  public course CameraFollow : MonoBehaviour {      public Transform followTransform;     public BoxCollider2D mapBounds;      individual float xMin, xMax, yMin, yMax;     private float camY,camX;     individual bladder camOrthsize;     individual bladder cameraRatio;     private Camera mainCam;     individual Vector3 smoothPos;     public float smoothSpeed = 0.5f;      private void Offset()     {         xMin = mapBounds.premises.min.10;         xMax = mapBounds.bounds.max.10;         yMin = mapBounds.premises.min.y;         yMax = mapBounds.bounds.max.y;         mainCam = GetComponent<Photographic camera>();         camOrthsize = mainCam.orthographicSize;         cameraRatio = (xMax + camOrthsize) / ii.0f;     }     // Update is called once per frame     void FixedUpdate()     {         camY = Mathf.Clamp(followTransform.position.y, yMin + camOrthsize, yMax - camOrthsize);         camX = Mathf.Clamp(followTransform.position.ten, xMin + cameraRatio, xMax - cameraRatio);         smoothPos = Vector3.Lerp(this.transform.position, new Vector3(camX, camY, this.transform.position.z), smoothSpeed);         this.transform.position = smoothPos;                       } }        

Simply we will add a smoothPos and a smoothSpeed variable. So in our fixedupdate method we volition take our current position, pass in our clamped position and lerp at the polish speed.

This volition give us that smooth camera motility you volition need in your 2d platformer game.

Unity camera motility Q&A

Unity 2d how to make photographic camera follow player?

There are a few methods of doing this. One of which is to parent your camera to your role player. This is the nearly simple method. The other is to employ a c# script to control the camera motion. Another method is using features from cinemachine.

How to brand photographic camera follow player position and rotation unity 3d?

You can utilise a c# script to control the photographic camera and make information technology motility relative to the player transform. You tin can control this on the x,y and z axis to create unlike types of camera follows. Like pinnacle down, side scrolling, 3rd person and 1st person photographic camera follows.

How to make the unity photographic camera follow behind player?

The simplest method is to parent your principal photographic camera to your player and first it'southward position slightly behind the histrion. For more than advanced camera follows you may want to employ a c# script to control the camera.

How do I add unity 2d camera premises?

To do this you need to create a bounding box which y'all can go the bounds from. So restrict your camera transform using mathf.clamp and proceed it within the bounds of the bounding box.

Some last words

If y'all liked this tutorial. Please consider sharing information technology on social media or supporting me on youtube past subscribing to my channel here: Subscribe on YouTube. Also consider checking out my course on building a unity 3d metropolis architect hither: Class. Check out some of my other blog posts and tutorials here:

Source: https://generalistprogrammer.com/unity/unity-2d-how-to-make-camera-follow-player/

Posted by: childfrichis.blogspot.com

0 Response to "How To Make The Camera Follow The Player In Unity"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel