Skip to content

Instantly share code, notes, and snippets.

@rutcreate
Created May 30, 2015 10:33
Show Gist options
  • Save rutcreate/dc2065f39f0d41e5f3fb to your computer and use it in GitHub Desktop.
Save rutcreate/dc2065f39f0d41e5f3fb to your computer and use it in GitHub Desktop.
Unity3d: 2D Pixel Perfect Camera
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
namespace RutCreate {
[ExecuteInEditMode]
public class CameraLayout : MonoBehaviour {
public Vector2 referenceResolution = new Vector2(800f, 600f);
public float referencePixelPerUnit = 100f;
public Color faceColor = new Color(0f, 0f, 0f, 0f);
public Color outlineColor = new Color(1f, 1f, 1f);
private void Start() {
Reset();
}
public void Reset() {
CanvasScaler[] scalers = FindObjectsOfType<CanvasScaler>();
foreach (CanvasScaler scaler in scalers) {
scaler.referenceResolution = referenceResolution;
scaler.referencePixelsPerUnit = referencePixelPerUnit;
}
Camera.main.orthographicSize = referenceResolution.y / referencePixelPerUnit / 2f;
Camera.main.transform.localPosition = Vector3.zero + Vector3.back * 10f;
}
private void OnDrawGizmos() {
DrawCameraRegion();
}
private void DrawCameraRegion() {
Vector3 position = Camera.main.transform.position;
Vector2 size = Utils.GetCameraSizeInUnit();
Vector3[] vertices = {
new Vector3(position.x - size.x * 0.5f, position.y + size.y * 0.5f, transform.position.z),
new Vector3(position.x + size.x * 0.5f, position.y + size.y * 0.5f, transform.position.z),
new Vector3(position.x + size.x * 0.5f, position.y - size.y * 0.5f, transform.position.z),
new Vector3(position.x - size.x * 0.5f, position.y - size.y * 0.5f, transform.position.z)
};
UnityEditor.Handles.DrawSolidRectangleWithOutline(vertices, faceColor, outlineColor);
}
}
}
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace RutCreate {
[CustomEditor(typeof(CameraLayout))]
public class CameraLayoutInspector : Editor {
public override void OnInspectorGUI() {
DrawDefaultInspector();
CameraLayout camLayout = target as CameraLayout;
if (GUILayout.Button("Reset position and size")) {
camLayout.Reset();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment