using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class PixelPerfectSprite : MonoBehaviour
{
    // NOTE: This script should be setted to be executed after every other script. This
    //       can be done in Unity in Edit->Project Settings->Script Execution Order

    private void Update()
    {
        //if (transform.position.x % (1 / PixelPerfectCamera.PixelsPerUnit) != 0 ||
        //    transform.position.y % (1 / PixelPerfectCamera.PixelsPerUnit) != 0)
        {
            float newX = GetNearestMultipleValue(transform.parent.position.x, 1f / PixelPerfectCamera.PixelsPerUnit);
            float newY = GetNearestMultipleValue(transform.parent.position.y, 1f / PixelPerfectCamera.PixelsPerUnit);
            transform.position = new Vector3(newX, newY, transform.position.z);
        }
    }

    /// <summary>
    /// Return the value, multiple of 'multiple', nearest to 'value'
    /// </summary>
    /// <param name="value"></param>
    /// <param name="multiple"></param>
    /// <returns></returns>
    private float GetNearestMultipleValue(float value, float multiple)
    {
        return GetTruncated((float)System.Math.Round(
                     (value / (float)multiple),
                     System.MidpointRounding.AwayFromZero
                 ) * multiple, 2);
    }

    private static float GetTruncated(float value, int decimalPlaces)
    {
        double mult = System.Math.Pow(10.0, decimalPlaces);
        double result = System.Math.Truncate(mult * value) / mult;
        return (float)result;
    }
}
