Created
February 3, 2014 22:00
-
-
Save Hamcha/8793314 to your computer and use it in GitHub Desktop.
Unity3D Top down (2D) Weighed Camera
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class CameraTracking : MonoBehaviour | |
{ | |
public struct CameraObject | |
{ | |
public GameObject Object; | |
public float Weight; | |
} | |
public List<CameraObject> Objects; | |
public Vector3 targetPosition; | |
public float targetScale; | |
public float scaleTime; | |
public float posTime; | |
private float scaleVelocity; | |
private Vector3 posVelocity; | |
void Start() | |
{ | |
Objects = new List<CameraObject>(); | |
} | |
void FixedUpdate() | |
{ | |
if (Objects.Count < 1) return; | |
Vector3 position = Vector3.zero; | |
float totalWeight = 0f; | |
foreach (CameraObject c in Objects) | |
{ | |
position += c.Object.transform.position * c.Weight; | |
totalWeight += c.Weight; | |
} | |
position /= totalWeight; | |
targetPosition = position; | |
targetPosition.z = -10f; | |
} | |
void Update() | |
{ | |
camera.orthographicSize = Mathf.SmoothDamp(camera.orthographicSize, targetScale, ref scaleVelocity, scaleTime); | |
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref posVelocity, posTime); | |
} | |
public void Add(GameObject obj, float weigth) | |
{ | |
CameraObject camObj; | |
camObj.Object = obj; | |
camObj.Weight = weigth; | |
Objects.Add(camObj); | |
} | |
public void Remove(GameObject obj) | |
{ | |
foreach (CameraObject c in Objects) | |
{ | |
if (c.Object == obj) | |
{ | |
Objects.Remove(c); | |
return; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment