# How to do pixel perfect movement with Unity3D?

How would you be able to make sprites move pixel by pixel in Unity3D? I've tried the following things.

• int x = (int) transform.position.x;

• int x = Mathf.FloorToInt(transform.position.x);

• int x = Mathf.RoundToInt(transform.position.x);

I don't know what else to try

Because I'm making an SNES looking game, and when things move, there is very bad pixel crawl in the sprites.

• Depending on what you mean by "pixel crawl", this question might be relevant. Commented Dec 17, 2015 at 21:04

I've done several pixel perfect games in Unity (the latest one.

Your first thought is the one I use, I cast every position as an integer. Something like :

Vector2 pos = transform.position;
Vector2 clamped_position = new Vector2((int)pos.x,(int)pos.y);
transform.position = clamped_position;

However if you're interested in movement it's a little bit complex but not too hard. The trick here is to update a variable with movement value (in pixel per second). Once the variable describes a movement greater than one pixel, you know that you have to move your GameObject.

Here is what you can find in the LateUpdate method of my GameObject:

private void LateUpdate()
{
// Clamp the current movement
Vector2 clamped_movement = new Vector2((int)_movement.x, (int)_movement.y);
// Check if a movement is needed (more than 1px move)
if (clamped_movement.magnitude >= 1.0f)
{
// Update velocity, removing the actual movement
_movement= _movement- clamped_movement;
if (clamped_movement != Vector2.zero)
{
// Move to the new position
transform.position = ClampVector(transform.position) + clamped_movement;
}
}
}

And here is how I update the _movement variable when player wants to go left :

public void GoLeft()
{
// speed is defined in pixel per second.
_movement.x -= speed * Time.deltaTime;
}

With that in mind you just have to take care of the orthographic size of your camera. Using this simple trick you can be sure that your main camera is correctly set up, and everything should work out.

I hope it helps.

• Dood your marvel game looks nice.
– Almo
Commented Dec 17, 2015 at 21:00