banner



How To Make Camera Follow Player Sprite Kit

So you have a game either in 2d or 3d which you need the photographic camera to follow the player. In this tutorial nosotros will be discussing the different methods how yous tin can use unity 2d and how to make the camera follow the player in your game. We will look at bones principles of doing this in unity 2d.

So to do this in 3d is very like, you will just make use of the z axis as well depending on the view you take in your game.

Whether that be meridian downward, side scrolling or offset or third person.

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

First nosotros need to setup a very bones unity 2d projection with a player moving in our scene. So I will setup a square as our actor moving around left, correct,upwards and downwardly.

With this we will just add a bones background so we get some depth in our 2d earth. From in that location nosotros will put together a unity 2d photographic camera movement which will allow for a top down role player camera follow.

Nosotros will then become ahead and add some bounds to our camera so nosotros tin can limit our photographic camera motion.

To start we create a new unity second projection.

Unity 2d how to make camera follow player

We volition start off by adding a elementary histrion every bit a square sprite.

So go ahead and right click in our assets folder and create a foursquare sprite with the beneath steps in the screenshots.

unity camera follow behind player

Rename our foursquare 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 ahead and add a rigidbody2d component on the correct past clicking on add component. So alter the rigidbod2d settings to exist kinematic.

Once done permit's create a actor movement script.

unity 2d platformer movement

Call that role player movement.

unity 2d camera bounds

Drag and drib that onto your role player game object like then.

unity camera follow player 3rd person

At present go ahead and open up the player move script in visual studio. Replace the code in that script with this.

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

At present y'all should have a moving player when you hit play in unity. Let'due south just add a bones background. I fabricated this i in inkscape very quickly.

unity camera follow player rotation

And so dragging that into our unity project we now take.

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

Simplest player camera follow and movement

The simplest way to do a photographic camera follow is to just kid our camera to our actor like this.

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

So if you accept done this and yous have moved your player to the edge of the screen you have probably figured out that this is non the most efficient way.

As your player may exist able to become out of the bounds of the screen so will your photographic camera view. So you will end upwards with something similar this.

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

So with this method we have very little control over our camera'due south transform, it'due south all dependent on the player transform.

A amend method is for us to rather apply a script.

Unity second player follow and photographic camera movement script

So go ahead and create a new c# script and phone call it photographic camera follow like this.

2d camera
2d camera

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

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

In information technology'southward almost basic form this is what y'all will need to make the photographic camera follow your player with a script. So simply put we declare a followTransform, this will be a our histrion's transform we will be post-obit with our camera.

We then in fixedupdate change our photographic camera transform position to that of our player but on the x and y axis because nosotros are moving in 2d space.

Become ahead now save this and add this to your photographic camera. Like so:

Likewise drag your histrion into the follow transform slow similar above. If you run your player photographic camera follow projection at present your camera should be following your player.

Well this is only one-half the story. Let us at present implement some camera bounds so our player won't go outside our background.

Unity second camera premises

To create a camera premises you firstly demand to create a way of measuring premises. You tin do this on our background which nosotros want to restrict our photographic 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 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 brand information technology restrict the bounds on our camera.

          using System.Collections; using System.Collections.Generic; using UnityEngine;  public class CameraFollow : MonoBehaviour {      public Transform followTransform;     public BoxCollider2D mapBounds;      individual float xMin, xMax, yMin, yMax;     individual bladder camY,camX;     private float camOrthsize;     private bladder cameraRatio;     private Camera mainCam;      individual void Start()     {         xMin = mapBounds.bounds.min.x;         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 one time 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 you start await at. However information technology is quite simple. First thing we added to our script is to go our mapBounds which is a boxcollider2d which accept alleged every bit public.

Nosotros then declare a few float variables for our xMin,xMax,yMax,yMin these will hold our min and max bounds from our boxcollider2d. And so 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 agree our main camera.

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

Subsequently this we go the orthographic size of our photographic camera.

Then we calculate the horizontal size based off the half size of the camera ortho and add together that to the maximum size on the ten of our bounds and but divide that by two.

We at present know how far we can motility on the x axis earlier our photographic camera will go out of view. Nosotros split specifically by 2.0f to continue the calculation every bit a float value so we don't lose precision.

Finally in our fixedupdate method nosotros clamp down our variables and offset them by the half size of our camera ortho by adding and subtracting them to their relevant positions.

Yous may need to go through this script a few times to full understand. One time you got that downwardly. Make y'all add your script to your photographic camera in unity.

Too as dragged your background into the map bounds slot.

When you run this you should end up with something that functions similar this.

Unity 2d camera bounds demonstration

So as you run across your thespian will approach the premises and the camera volition finish following at that point.

If you have done all this correctly y'all should have a script which allows the photographic camera to follow the player to the T in both position and rotation.

Adapting this for unity 2nd platformer movement

This is actually very simple. With what you lot accept here yous will exist able to do this just fine. You lot may want to just add some smoothing with your camera motion though.

You tin do this using a lerp function. So hither is how we will modify the c# script to make the player camera follow motion smooth.

          using Arrangement.Collections; using System.Collections.Generic; using UnityEngine;  public grade CameraFollow : MonoBehaviour {      public Transform followTransform;     public BoxCollider2D mapBounds;      individual float xMin, xMax, yMin, yMax;     private bladder camY,camX;     private float camOrthsize;     private float cameraRatio;     private Camera mainCam;     private Vector3 smoothPos;     public bladder smoothSpeed = 0.5f;      private void Beginning()     {         xMin = mapBounds.bounds.min.x;         xMax = mapBounds.premises.max.x;         yMin = mapBounds.bounds.min.y;         yMax = mapBounds.bounds.max.y;         mainCam = GetComponent<Camera>();         camOrthsize = mainCam.orthographicSize;         cameraRatio = (xMax + camOrthsize) / two.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;                       } }        

Only we will add a smoothPos and a smoothSpeed variable. Then in our fixedupdate method we will have our current position, pass in our clamped position and lerp at the shine speed.

This volition requite u.s.a. that smooth photographic camera movement you will need in your 2d platformer game.

Unity photographic camera movement Q&A

Unity 2d how to brand camera follow player?

At that place are a few methods of doing this. I of which is to parent your photographic camera to your player. This is the most elementary method. The other is to utilize a c# script to control the photographic camera movement. Another method is using features from cinemachine.

How to make camera follow thespian position and rotation unity 3d?

You lot can use a c# script to command the photographic camera and make it movement relative to the player transform. Yous can control this on the x,y and z axis to create unlike types of photographic camera follows. Like top downwardly, side scrolling, third person and 1st person camera follows.

How to make the unity camera follow behind thespian?

The simplest method is to parent your main camera to your actor and kickoff it'south position slightly behind the actor. For more avant-garde camera follows y'all may want to use a c# script to control the camera.

How exercise I add together unity 2d camera premises?

To do this you need to create a bounding box which you can become the premises from. Then restrict your camera transform using mathf.clamp and keep information technology 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 past subscribing to my channel here: Subscribe on YouTube. As well consider checking out my class on building a unity 3d metropolis architect here: Course. Cheque 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: kosstrumsess.blogspot.com

0 Response to "How To Make Camera Follow Player Sprite Kit"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel