Skip to content

Instantly share code, notes, and snippets.

@Hamcha
Created February 3, 2014 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hamcha/8793314 to your computer and use it in GitHub Desktop.
Save Hamcha/8793314 to your computer and use it in GitHub Desktop.
Unity3D Top down (2D) Weighed Camera
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