Skip to content

Instantly share code, notes, and snippets.

@toxicFork
Created July 7, 2015 19:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save toxicFork/5d0e012fce532d9695b9 to your computer and use it in GitHub Desktop.
Save toxicFork/5d0e012fce532d9695b9 to your computer and use it in GitHub Desktop.
Pixel -> World coordinates | World -> Pixel coordinates
private static Vector2 WorldToPixelCoords(Vector3 projectedPoint, Sprite sprite, Transform transform)
{
var textureRect = sprite.textureRect;
var spriteBounds = sprite.bounds;
var localPoint = transform.InverseTransformPoint(projectedPoint);
localPoint.x = (localPoint.x - spriteBounds.min.x) / (spriteBounds.size.x);
localPoint.y = (localPoint.y - spriteBounds.min.y) / (spriteBounds.size.y);
return new Vector2((textureRect.xMin + textureRect.width * localPoint.x),
(textureRect.yMin + textureRect.height * localPoint.y));
}
private static Vector3 PixelToWorldCoords(Vector2 pixelCoords, Sprite sprite, Transform transform)
{
var textureRect = sprite.textureRect;
var spriteBounds = sprite.bounds;
var updatedLocalPoint = new Vector2((pixelCoords.x - textureRect.xMin)/textureRect.width,
(pixelCoords.y - textureRect.yMin)/textureRect.height);
var pointToTransform = new Vector2((updatedLocalPoint.x)*spriteBounds.size.x + spriteBounds.min.x,
(updatedLocalPoint.y)*spriteBounds.size.y + spriteBounds.min.y);
return transform.TransformPoint(pointToTransform);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment