Pixel of a Sprite under the MousePosition
It sounds almost easy, but I can't find any solution for two days already: I have a 2d object(its a sheet of paper) with some coordinates, and when I click on it I want to get the pixel where I clicked. And then draw around this pixel. This specific pixel where I clicked must be not in world coordinates(not a screen pixel), but a pixel of this sheet of paper. How do I do it?
Answer by Lazybones94 · Sep 25, 2015 at 05:57 PM
Solved it with big effort. To get the needed pixel, I had to cast two rays: one ray from the bottom middle, another from left middle parts of the screen. This gave me two Vector2 with the least X and Y positions of my sheet of paper in world coordinates. Then I get the mouse position in world coordinates, and calculate the length of X line from the least X position to mousePosition.x and the length of the same line in Y axis. Then I calculate the relation of these two lines to the full X and Y length, and use this relations to calculate the needed pixel. Here is the code example:
Vector2 screenMidX = new Vector2(Screen.width * 0.5f, 0); Vector2 screenMidY = new Vector2(0, Screen.height * 0.5f); RaycastHit2D YPointHit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(screenMidX), Vector2.up); YLowerPoint = YPointHit.point; RaycastHit2D XPointHit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(screenMidY), Vector2.right); XLowerPoint = XPointHit.point; float XdeltaPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition).x - XLowerPoint.x; float YdeltaPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition).y - YLowerPoint.y; float Xpart = 1 /( (paper_currentSprite.bounds.size.x * paper_current.transform.lossyScale.x) / XdeltaPoint); float Ypart = 1 /( (paper_currentSprite.bounds.size.y * paper_current.transform.lossyScale.y) / YdeltaPoint); int pixelsX = paper_currentSprite.texture.width; int pixelsY = paper_currentSprite.texture.height; int posX = (int)(pixelsX * Xpart); int posY = (int)(pixelsY * Ypart);
And the posX and posY integers represent the position of the needed pixel. Hope somebody will find this post useful one day!
Your answer
Follow this Question
Related Questions
Sprites have discolored patches / color bleeding 0 Answers
Can you use transform.Translate with pixels instead of units? 0 Answers
Loading array of objects by using parent folder name in asset bundle? 0 Answers
Is there a quick way to convert a sprite sheet of sprites to a bunch of prefabs? 0 Answers
Moving MANY objects together 0 Answers