1. PolCPP
  2. Twisted Potions Double Trouble

Source

Twisted Potions Double Trouble / Assets / scripts / CameraFollow.cs

using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {
	
	// The player character to follow.
	public Transform target;
	// Our Gui (which will follow the camera)
	public Transform gui;
	
	private Vector3 halfScreen = new Vector3(0.5f,0.5f,0);
	private Vector3 quarterScreen = new Vector3(0.25f,0.25f,0);
	
	private Vector3 halfDelta;
	private Vector3 quarterDelta;
	
	// The zeroPoint will be used to know when the 0,0 of the camera is showing it's 0,0
	// The onePoint  does the same on the other side.
	private Vector3 zeroPoint;
	private Vector3 onePoint;

	private int map_length = 1000;
	
	private Vector3 destination;	

	void Update () {
	    if(target) {	        
			destination = Vector3.zero;
			// We want to know if our target will go farther than 50% screen and
			// less than 25%, in both up and down directions. 
			// So we'll get the delta of our target and the point of half and quarter the screen. 			
			halfDelta = target.position - camera.ViewportToWorldPoint(halfScreen);						
			quarterDelta = target.position - camera.ViewportToWorldPoint(quarterScreen);						
			
			// Now we check if we need to move. 
			// Since we're going pixel based the camera will move in 1 unit ranges (nondecimal).
			if (halfDelta.x > 0)
				destination.x = 1;
			if (halfDelta.y > 0)
				destination.y = 1;	
			if (quarterDelta.x < 0)
				destination.x = -1;
			if (quarterDelta.y < 0)
				destination.y = -1;	
			
			// Now before we update, we check if we're not on the 0 edge. 
			// Max Length will be done later on
			// Plus we only check it if we're moving
			if (destination != Vector3.zero) {
				zeroPoint = camera.ViewportToWorldPoint(Vector3.zero);						
				onePoint = camera.ViewportToWorldPoint(Vector3.one);
				if (zeroPoint.x <= 0 && destination.x < 0)
					destination.x = 0;
				if (onePoint.x >= map_length && destination.x > 0)
					destination.x = 0;
			}
			
			
			// FInally we update the camera
			transform.position = transform.position + destination;
			
			// We're moving the gui, altho the best way would be to place it fixed.
			if (gui) {
				gui.position = gui.position + destination;	
			}
		}		
	}
}