Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by lntoTheSky · Jun 12, 2016 at 05:17 PM · c#camerafollow playercollide

[Solved] How to Script a Camera That Follows the Player but Collides with the Edge of the Level

I'm designing a 2D top down game and, basically, I want a camera that follows the character when he is in the middle of the level, but as he approaches the edge of the level, the camera essentially collides with the edge of the level and stops following the character along that axis.

Here is an example of what I want from Zelda: Link to the Past: https://youtu.be/aBslMPvo7oo?t=6m3s

Notice how the camera follows Link, but stops as he approaches the edges of the dungeon and the room exits.

I tried to get this working for about 2 or 3 hours last night, between working through code and browsing for youtube videos.

The closest I could find to what I want is in this video: https://www.youtube.com/watch?v=u67fbxe8xxY

and here is the code:

 using UnityEngine;
 using System.Collections;
 
 public class CameraMovement : MonoBehaviour {
 
     public Transform target;
 
     public Vector2
         margin,
         smoothing;
 
     public BoxCollider2D bounds;
 
     private Vector3
         _min,
         _max;
 
     public bool isFollowing = true;
 
     private Camera myCam;
 
     public void cameraMovement(){
         var x = transform.position.x;
         var y = transform.position.y;
 
         if(isFollowing){
             if(Mathf.Abs(x - target.position.x) > margin.x){
                 x = Mathf.Lerp(x, target.position.x, smoothing.x * Time.deltaTime);
             }
 
             if(Mathf.Abs(y - target.position.y) > margin.y){
                 y = Mathf.Lerp(y, target.position.y, smoothing.y * Time.deltaTime);
             }
         }
 
         var cameraHalfWidth = GetComponent<Camera>().orthographicSize * ((float)Screen.width / Screen.height);
 
         x = Mathf.Clamp(x, _min.x + cameraHalfWidth, _max - cameraHalfWidth);
         y = Mathf.Clamp(y, _min.y + myCam.orthographicSize, _max.y - myCam.orthographicSize);
 
         transform.position = new Vector3(x, y, transform.position.z);
     }
 
     // Use this for initialization
     void Start () {
         _min = bounds.bounds.min;
         _max = bounds.bounds.max;
         myCam.orthographicSize = 4.5f;
     }
     
     // Update is called once per frame
     void Update () {
         cameraMovement();
     }
 }

The problem with all of the code and videos I have found so far is that the ones that successfully cause the camera to collide with the edge of the level also include a feature called "smoothing" where the camera continues moving for a few frames past the player when he stops, and then snaps back to the player or stays off center. I HATE this feature and do not want anything to do with it.

I'm hoping someone here knows how to script the camera to behave like it does in the Zelda video, or can point me down the right path to figure this problem out. Thanks a bunch for reading the wall of text, and let's solve this!

EDIT: I solved this problem (awhile ago actually, forgot to update :P).

Here is the code:

 using UnityEngine;
 using System.Collections;
 
 public class CameraControl : MonoBehaviour {
 
     public GameObject player;
     public Transform highWall;
     public Transform lowWall;
     public Transform rightWall;
     public Transform leftWall;
 
     private float yMax;
     private float yMin;
     private float xMax;
     private float xMin;
 
     // Use this for initialization
     void Start(){
     }
     
     // Update is called once per frame
     void Update(){
         yMax = highWall.transform.position.y;
         yMin = lowWall.transform.position.y;
         xMax = rightWall.transform.position.x;
         xMin = leftWall.transform.position.x;
 
         //if within the bounds, camera locks onto player
         if(player.transform.position.y < yMax && player.transform.position.y > yMin){
             transform.position = new Vector3(player.transform.position.x, player.transform.position.y, -110.0f);
         }
 
         //if player is above/below the y axis binders, camera locks to player on xAxis and stays stationary 
         //on yAxis
         if(player.transform.position.y > yMax){
             transform.position = new Vector3(player.transform.position.x, yMax, -110.0f);
         }else if(player.transform.position.y < yMin){
             transform.position = new Vector3(player.transform.position.x, yMin, -110.0f);
         }
 
         //if player is right/left of the xAxis binders, camera locks to player on yAxis and stays stationary 
         //on xAxis
         if(player.transform.position.x > xMax){
             transform.position = new Vector3(xMax, player.transform.position.y, -110.0f);
         }else if(player.transform.position.x < xMin){
             transform.position = new Vector3(xMin, player.transform.position.y, -110.0f);
         }
 
         //if player is above the yAxis binder, and to the right of the xAxis, the camera stays stationary
         if(player.transform.position.y > yMax && player.transform.position.x > xMax){
             transform.position = new Vector3(xMax, yMax, -110.0f);
         }
         //if player is above the yAxis binder, and to the left of the xAxis, the camera stays stationary
         if(player.transform.position.y > yMax && player.transform.position.x < xMin){
             transform.position = new Vector3(xMin, yMax, -110.0f);
         }
         //if player is below the yAxis binder, and to the right of the xAxis, the camera stays stationary
         if(player.transform.position.y < yMin && player.transform.position.x > xMax){
             transform.position = new Vector3(xMax, yMin, -110.0f);
         }
         //if player is below the yAxis binder, and to the left of the xAxis, the camera stays stationary
         if(player.transform.position.y < yMin && player.transform.position.x < xMin){
             transform.position = new Vector3(xMin, yMin, -110.0f);
         }
     }
 }

I can answer any questions about the code if people ask, but it's a fairly straightforward solution which attaches trigger colliders to the camera and if the character moves past the colliders, the camera stops moving on that axis.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Mmmpies · Jun 12, 2016 at 05:46 PM

You may well have watched this already

https://www.youtube.com/watch?v=KMhPYf9zzlA

Now consider this, in that video they use your hated smoothing but it's controlled by making the camera move slowly, increase that and you'll not see the smoothing.

It also doesn't cover stopping the camera at the edge of the screen but it does show how to change the target so if you get to a point where the camera's going to go off the edge of the screen pinpoint the player location and set your target as that point rather than the moving player.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image lntoTheSky · Jun 13, 2016 at 06:22 AM 0
Share

Yes, I have seen the video and I'm using code similar to what he uses but the code is much simpler, simply two lines in the update that reads: if (target) { transform.position = target.transform.position + new Vector3(0.0f, 0.0f, -110.0f);

I won't need the camera to smooth the way it does in the video, so this is just a quick and easy way to do everything else.

It seems like stopping the camera is the hard part though! None of the Zelda-likes I've looked at actually show you how to do this, even though it's a fundamental aspect of how the Zelda camera moves...

avatar image
0

Answer by lntoTheSky · Jun 14, 2016 at 12:55 AM

Thanks for the help guys, I think I may have figured it out.

I basically threw out the code I have, since I don't want to use linear interpolation to smooth the camera. Instead, I've used a simple line of code for tracking the character:

transform.position = target.transform.position + new Vector3 (0, 0, -110.0f)

I then put some code under FixedUpdate instead of Update so the the Physics and Transform calculations are done at the same time in order to solve the pesky jittering I was getting whenever the character collided with a wall.

Finally I'm going to add colliders around the edges of the and have an OnCollisionEnter2D which uses the code from this guide: https://www.toptal.com/unity-unity3d/2d-camera-in-unity to get the camera to stop tracking along the axis where the collision occurs.

I'm at work now so I can't test any of this, but that should be it, with a little more code. Was wondering what people thought about this idea, thanks a bunch!

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Mmmpies · Jun 14, 2016 at 08:08 AM 0
Share

Seems like a good plan but you might also want to look at this for finding the edge of the camera

http://answers.unity3d.com/questions/501893/calculating-2d-camera-bounds.html

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

169 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Unity3D FollowCam not following player vehicle 0 Answers

camera falling down when following player!! 1 Answer

Roll a ball, treating where the camera is rotating as forward? 0 Answers

How to make a camera follow a ball from behind? c# 3 Answers

Clamping when Zoom changes? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges