Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
avatar image
1
Question by vahid62 · Nov 15, 2014 at 01:31 PM · cameramovementlimit

Limiting camera movement (2d map)

Hi,

I have made a map for my 3D scene and I have placed a camera in the sky looking down. With below code (find here) I can pan the camera and zoom in and out.

My question is, how can I limit camera movement to the boundaries of map?

I've seen several threads on this subject but I can't figure out it.

  using UnityEngine;
  using System.Collections;
  
  public class DragMap : MonoBehaviour {
      private float dist;
      private Vector3 v3OrgMouse;
      
      void Start () {
          dist = transform.position.y;  // Distance camera is above map
      }
      
      void Update () {
          if (Input.GetMouseButtonDown (0)) {
              v3OrgMouse = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
              v3OrgMouse = Camera.main.ScreenToWorldPoint (v3OrgMouse);
              v3OrgMouse.y = transform.position.y;
          } 
          else if (Input.GetMouseButton (0)) {
              var v3Pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
              v3Pos = Camera.main.ScreenToWorldPoint (v3Pos);
              v3Pos.y = transform.position.y;
              transform.position -= (v3Pos - v3OrgMouse);
          }
          
          if (Input.GetAxis("Mouse ScrollWheel") < 0 ) // Scroll back 
             orthographicSize+=10;
 
          if (Input.GetAxis("Mouse ScrollWheel") > 0 ) // Scroll forward
             orthographicSize-=10;
      }
  }


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
7
Best Answer

Answer by robertbu · Nov 16, 2014 at 09:41 PM

Let me assume you were smart and setup your map so that it's origin is at (0,0,0). For an Orthographic camera, the camera sees 1/2 of the screen height, so you can get how much it sees horizontally by:

  Camera.main.orthographicSize * Screen.width / Screen.height * 2.0;

This subtracted from the screen width and divided by 2.0 will give you the horizontal limits of the camera. The clamping values must be recalculated each time the camera is zoomed. Putting it together with your existing code, produces:

 using UnityEngine;
 using System.Collections;
 
 public class DragMap : MonoBehaviour {
     private float dist;
     private Vector3 v3OrgMouse;
 
     public float mapWidth = 20.0f;
     public float zoomFactor = 0.4f;
     public float minZoom = 0.4f;
 
     private float maxZoom = 25.0f;
     private float minX, maxX;
     
     void Start () {
         dist = transform.position.y;  // Distance camera is above map
         CalcMinMax();
         maxZoom = Camera.main.orthographicSize * Screen.height / Screen.width * 2.0f;
     }
     
     void Update () {
         if (Input.GetMouseButtonDown (0)) {
             v3OrgMouse = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
             v3OrgMouse = Camera.main.ScreenToWorldPoint (v3OrgMouse);
             v3OrgMouse.y = transform.position.y;
         } 
         else if (Input.GetMouseButton (0)) {
             var v3Pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
             v3Pos = Camera.main.ScreenToWorldPoint (v3Pos);
             v3Pos.y = transform.position.y;
             transform.position -= (v3Pos - v3OrgMouse);
         }
 
         float sw = Input.GetAxis ("Mouse ScrollWheel");
         if (Mathf.Abs (sw) > 0.01f) {
             Camera.main.orthographicSize += sw * zoomFactor;
             Camera.main.orthographicSize = Mathf.Clamp (Camera.main.orthographicSize, minZoom, maxZoom);
             CalcMinMax();
         }
         Vector3 pos = transform.position;
         pos.x = Mathf.Clamp (pos.x, minX, maxX);
         transform.position = pos;
     }
 
     void CalcMinMax() {
         float height = Camera.main.orthographicSize * 2.0f;
         float width  = height * Screen.width / Screen.height;
         maxX = (mapWidth - width) / 2.0f;
         minX = -maxX;
     }
 }

Note that I also added some limits to the zooming so that the use cannot zoom in to a negative number nor zoom out beyond the edges of the map.

Comment
Add comment · Show 3 · 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 vahid62 · Nov 17, 2014 at 11:33 AM 0
Share

Thanks robertbu. It works perfect

avatar image Argl · Mar 10, 2016 at 10:50 AM 0
Share

Thank you a lot, saved me a day of work here.

avatar image ZatriX_ZA · May 02, 2017 at 03:05 PM 0
Share

Clear and simple. Adding 2nd axis clamp was a breeze.

avatar image
2

Answer by Eck · Nov 16, 2014 at 09:50 PM

Well, you're calculating where the new cameraPosition is going to be. And I'm assuming you know the map dimensions. So, before you set the camera's transform.position, limit those values to the map dimensions.

 // Some public members should be set to your map's dimensions
 public float minX;
 public float maxX;
 public float minZ;
 public float maxZ;
 
 
 // Your code
 else if (Input.GetMouseButton (0))
 {
     var v3Pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, dist);
     v3Pos = Camera.main.ScreenToWorldPoint (v3Pos);
     v3Pos.y = transform.position.y;
 
     // New limiting code
     // Calculate the new cameraPosition (the same a you did)
     Vector3 newCameraPosition = transform.position - (v3Pos - v3OrgMouse);
     // Now clamp the vector to our min/max's.
     newCameraPosition = new Vector3
     (
         Mathf.Clamp(newCamperaPosition.x, minX, maxX),
         newCameraPosition.y, // Could also min/max the y if you like.
         Mathf.Clamp(newCamperaPosition.z, minZ, maxZ)
     );
 
     transform.position = newCameraPosition;
 }
 

I didn't compile this code, but you should be able to get it working if there's bugs. Let me know if there are any issues.

  • Eck

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 vahid62 · Nov 17, 2014 at 11:48 AM 0
Share

Thanks Eck . As the robertbu Explained, OrthographicSize must be used for calculating boundaries in zoo$$anonymous$$g. Without using scroll for zoom this code works good.

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

29 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

Related Questions

Issue with clamping player to camera view 2 Answers

Using Mathf.Clamp To Limit Camera Movement 0 Answers

Joystick direction To Camera direction Help!!!XD 1 Answer

How to set maximum distance for a player going left and right? 1 Answer

character movement follows the direction of camera -1 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