Created
May 30, 2015 10:33
-
-
Save rutcreate/dc2065f39f0d41e5f3fb to your computer and use it in GitHub Desktop.
Unity3d: 2D Pixel Perfect Camera
This file contains 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 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); | |
} | |
} | |
} |
This file contains 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 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