Round position


I have a Rigidbody2D (the player) that i move by setting its velocity, i’m trying to restrict its position to multiples of 0.01 so that it moves pixels by pixels but when i round it’s position it messes up the movements completely, this is probably happening because i’m setting it’s velocity and position at the same time, is there a way to round my Rigidbody2D’s position without interfering with it’s velocity based movements?


I assume that it’s not that important that the collider is snapped to a certain pixel. So, just let the rigidbody move smoothly like it’s suppoed to be, but put the SpriteRenderer on a child gameObject and add a little script to it that snaps the child to the screen pixels. I have written this for my own 2d project:

/*How to use:
1. Make the GO that contains the SpriteRenderer a child of another GameObject which has not SpriteRenderer (either could have things like Colliders and other scripts).
2. Put the PixelPerfect script onto the child GO that contains the SpriteRenderer
3. Open the script and set the pixelsPerUnit value to whatever you want (1, 16, ...) depending on your resolution. If each tile is equal to one unity unit, then you would set to 16. If each pixel is equal to one Unity unit, then set it to 1. The variable is not public so that you can change the value inside the script and each instance of the script will be affected without having to go over each instance manually.
4. The script has the attribute [ExecuteInEditMode] so you can drag aroung the parent object and see that the child object which has the SpriteRenderer and PixelPerfect script snaps to whole pixels.
5. Note that since the Start function is not called in Edit mode, is is instead called in LateUpdate, but only if the game is not running.

using UnityEngine;
using System.Collections;
using System;

public class PixelPerfect : MonoBehaviour {
	private int pixelsPerUnit = 1;
	private float snapValue = 1;
	// Use this for initialization
	void Start () {
		snapValue = 1f / pixelsPerUnit;
	// Update is called once per frame
	void LateUpdate () {
		if(Application.isPlaying == false) {
			snapValue = 1f / pixelsPerUnit;
		Vector3 pos = transform.parent.position;
		pos = new Vector3((float)Math.Round(pos.x / snapValue) * snapValue, (float)Math.Round(pos.y / snapValue) * snapValue, (float)Math.Round(pos.z / snapValue) * snapValue);
		transform.position = pos;