'Unity: SetPixal on a texture at mouse position (2D)
I am trying to draw on a texture but I don't know the math to convert my mouse position to the texture position.
Currently, the code will draw on the texture but the coordinates are very off. If someone can help me with this I would appreciate it.
var mousePosition = Input.mousePosition;
var drawPosition = new Vector2(mousePosition.x, mousePosition.y);
for (int x = 0; x < brushSize; x++)
{
for (int y = 0; y < brushSize; y++)
{
m_Texture.SetPixel(x + (int)drawPosition.x, y + (int)drawPosition.y, Color.clear);
}
}
m_Texture.Apply();
Solution 1:[1]
Try this:
Vector2 pos;
void Update(){
RectTransformUtility.ScreenPointToLocalPointInRectangle(
parentCanvas.transform as RectTransform, Input.mousePosition,
parentCanvas.worldCamera,
out pos);
}
Assign the parentCanvas and use the pos.x and pos.y inside your for loops
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kitsomo |
