Created
July 7, 2015 19:57
-
-
Save toxicFork/5d0e012fce532d9695b9 to your computer and use it in GitHub Desktop.
Pixel -> World coordinates | World -> Pixel coordinates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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