Search code examples
c#unity-game-enginetexturesgame-developmenttexture2d

How to convert hit point to pixel points for Texture2D in Unity?


I have a game where you need to draw something on a plane with the mouse at the finish. I am raycasting mouse position with this:

if (Input.GetMouseButton(0))
        {
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                Vector3 mousePos = hit.point;
                Draw(mousePos);
            }
        }

In the Draw function, I use the SetPixel method to apply my changes to the texture:

public void Draw(mousePos) {
    //Dont know how to use mousePos
    Texture2D texture = new Texture2D(128, 128);
    GetComponent<Renderer>().material.mainTexture = texture;
    texture.SetPixel(x, y, color);
    texture.Apply();
}

But I could not make the conversion between Vector3 mousePosition to the (x,y) pair of texture pixel. How can I do the conversion?


Solution

  • You can use RaycastHit.textureCoord

    This will return the texture coordinate when a hit occurs.
    The object being hit MUST have a mesh collider on it for this to work.

    Vector2 pixelUV = hit.textureCoord;
    
    // Convert to image space
    //
    pixelUV.x *= texture.width; 
    pixelUV.y *= texture.height;
    
    texture.SetPixel((int)pixelUV.x, (int)pixelUV.y, Color.black);
    texture.Apply();
    

    This example is taken from the unity documents, and is found here