Camera Pinch/Zoom Constraints

Hi,

i can move my camera in certain areas (2D Movement). I constrain the movement with borders. Now if i zoom with the camera (changing orthographic size) the borders doesnt work anymore and i see more of the screen then i want. How to achieve that the borders for the cam will always be the same for every different orthographic size of the cam?

Thanks for the help.

I had to implement this recently in two games. I have the code, but probably can’t help you out today (I’m at work and have plans tonight). If no one else can help you, I will try to help sometime this weekend.
I sort of know how I did it, but I don’t want to give you false information so I’d need to check first, since it was a while ago.

wow this would be cool if you can post the script on the weekend. Thank you

In my game, I do this to constrain the camera :

	public void CheckMargins() {
		float margin = this.camera.orthographicSize;
		Vector3 p = transformCache.position;
		if(p.y<margin) {
			p.y = margin;
		}
		margin = 240f / 160f * this.camera.orthographicSize;
		if(p.x<margin) {
			p.x = margin;
		}
		margin = 1240f - margin;
		if(p.x>margin) {
			p.x = margin;
		}
		
		transformCache.position = p;
	}

Please note that this only restricts the camera in 3 directions.

great! Thank you Smag.

I have some quesions:

  1. transformCache is the camera position, right?
  2. do you call the method CheckMargins() after you changed the orthographic size?
  3. why do you use 240f / 160f and 1240 ?
  1. transformCache is the camera position, right?
    Yeah, that’s in a script attached to the camera, and it has a cached version of the transform.

  2. do you call the method CheckMargins() after you changed the orthographic size?
    I call it at the end of my update cycle, so after potential camera position changes and othographics size changes.

  3. why do you use 240f / 160f and 1240 ?
    My orthographic dize when zoomed normally is 160 (half the screen height). This makes one unity unit = one pixel.
    When scrolling, I need a horizontal margin of 240 on each side (half the screen, because the camera’s 0 point is in the center of the screen).
    So when the camera is zoomed normally, this :
    240f / 160f * this.camera.orthographicSize
    would result in just 240. But when the ortho size is 320 (zoomed out so you see twice as much), the margin would be 480 (which is twice as big).

For the top margin the formula would actually be this :

float margin = 160f / 160f * this.camera.orthographicSize;
(marginheight / normal-ortho-size * current-ortho-size)

But off course 160/160 is just one :slight_smile:

As for the 1240, that’s the scrollable area (the length of the level). That could be made dynamic.