Working with 2D Toolkit in Unity is great because if you need to make a 2D game that’s pixel-pefect (such as a pixel-art platformer like Agro-Aggro), then it’s as easy as a setting the Pixels Per Meter setting on 2D Toolkit’s camera.
2D Toolkit’s camera has another setting called Zoom Factor if you want your game to have big, chunky pixels. So, for example, if you want to have your game running at 1280×960, but you want the game to seem like it has a resolution of 320×240, you’d set a Zoom Factor of 4. And lets say you have set your Pixels Per Meter to 16. That means your game’s camera is going to be viewing 20 units by 15 units of your game space.
This is all well and good, if everything in your game is only moving in one-unit increments, which is not likely to happen in a platformer where things are sliding around in float-value increments through your game space. So, I needed a way for the sprites attached to the player’s game object to stick to that magnified pixel grid. Turns out it’s actually pretty simple.
Here’s the code….
using UnityEngine;
using System.Collections;
public class PixelGrid : MonoBehaviour {
Transform player;
private float offsetX, offsetY;
private float pPM; // pixels per meter
void Start() {
player = transform.parent;
offsetX = transform.localPosition.x;
offsetY = transform.localPosition.y;
pPM = tk2dCamera.Instance.CameraSettings.orthographicPixelsPerMeter;
}
void Update () {
Vector3 playerPos = player.position;
playerPos.x = Mathf.RoundToInt(playerPos.x * pPM) / pPM + offsetX;
playerPos.y = Mathf.RoundToInt(playerPos.y * pPM) / pPM + offsetY;
transform.position = playerPos;
}
}
Keep in mind that the sprite is parented to the actual player game object. So the character controller is what’s moving in float-values through the game space, but the game object that holds the sprite is a child of that character controller. The above code takes that child sprite and ensures that the sprite is only moving in game space increments equal to whole (zoomed) pixels.