Skip to content

Instantly share code, notes, and snippets.

@Azzizi
Last active August 29, 2015 14:00
Show Gist options
  • Save Azzizi/ed99d5096436342f8f13 to your computer and use it in GitHub Desktop.
Save Azzizi/ed99d5096436342f8f13 to your computer and use it in GitHub Desktop.
Scripts for snapping to virtual pixel boundaries in low-rez Unity games. made for use with 2D Toolkit-- for Unity 2D, change the metersPerPixel calculation.
using UnityEngine;
namespace FBD
{
public static class Extensions
{
public static Transform FindInHierarchy(this Transform t, string name)
{
for (int c = 0; c < t.childCount; c++)
{
Transform temp = t.GetChild(c);
if (temp.name == name)
return temp;
else
{
temp = temp.FindInHeirarchy(name);
if (temp != null)
return temp;
}
}
return null;
}
public static float RoundTo(float number, float roundTo)
{
return Mathf.Round(number / roundTo) * roundTo;
}
}
}
using UnityEngine;
using System.Collections.Generic;
namespace FBD
{
public class PixelSnap : MonoBehaviour
{
private float metersPerPixel;
private Vector3 realPosition = Vector3.zero;
// Use this for initialization
void Start()
{
PixelSnapCamera.RegisterSnapObject(this);
metersPerPixel = 1.0f / Camera.main.GetComponent<tk2dCamera>().CameraSettings.orthographicPixelsPerMeter;
}
void OnDestroy()
{
PixelSnapCamera.UnRegisterSnapObject(this);
}
public void PrepareRender()
{
realPosition = transform.position;
Vector3 temp = new Vector3(Extensions.RoundTo(transform.position.x, metersPerPixel),
Extensions.RoundTo(transform.position.y, metersPerPixel), 0f);
transform.position = temp;
}
public void PostRender()
{
transform.position = realPosition;
}
}
}
using UnityEngine;
using System.Collections.Generic;
namespace FBD
{
public class PixelSnapCamera : MonoBehaviour
{
private static List<PixelSnap> snapObjects;
void Start()
{
if (snapObjects == null)
snapObjects = new List<PixelSnap>();
}
void OnPreCull()
{
foreach (PixelSnap p in snapObjects)
p.PrepareRender();
}
void OnPostRender()
{
foreach (PixelSnap p in snapObjects)
p.PostRender();
}
public static void RegisterSnapObject(PixelSnap snapObj)
{
snapObjects.Add(snapObj);
}
public static void UnRegisterSnapObject(PixelSnap snapObj)
{
snapObjects.Remove(snapObj);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment