- Home /
painting program not drawing at cursor point on texture
I'm attempting to make a script that lets colors be painted on a texture, in kind of an MS Paint/Photoshop kind of fashion. It works by using setpixel and repeatedly applying to a blank texture set on an object layered below the camera while the mouse is pressed.
The script basically works, but there is one problem. When it paints the color does not appear at the cursor point, but rather offset to the right or left depending on which side the mouse is on.
The screenshot shows where the color dot appears when the cursor is clicked where it's positioned. I'm sure this has something to do with the mouse input not correlating with the position of pixels on the texture, but I'm not sure how to deal with it.
Any help would be greatly appreciated.
public class colorScript : MonoBehaviour {
//holds each drawing of the texture
Texture2D destTex;
//a vector to store the position of the mouse.
public Vector3 mousepos = new Vector3 (0, 0, 0);
//just a test color
public Color col = Color.red;
void Start()
{
//the screen width and height are store for the size of the new texture
int width = Mathf.FloorToInt(Screen.width);
int height = Mathf.FloorToInt(Screen.height);
//create a new texture to draw on
destTex = new Texture2D(width, height);
//create a new sprite using the texture
GetComponent<SpriteRenderer>().sprite = Sprite.Create(destTex, new Rect(Camera.main.rect.x, Camera.main.rect.y, destTex.width, destTex.height), new Vector2(0.5f, 0.5f),100f);
}
void Update()
{
//get the mouse position and feed it to paint() for coordinates if the button is pressed
mousepos = Input.mousePosition;
if (Input.GetMouseButton(0))
paint((int)mousepos.x, (int)mousepos.y);
}//end update
//a modified version of the circle script to draw full circles
public void paint (int cirX, int cirY)
{
int x, y, px, nx, py, ny, d;
int r = 10;
for (x = 0; x <= r; x++)
{
d = (int)Mathf.Ceil(Mathf.Sqrt(r * r - x * x));
for (y = 0; y <= d; y++)
{
px = cirX + x;
nx = cirX - x;
py = cirY + y;
ny = cirY - y;
destTex.SetPixel(px, py, col);
destTex.SetPixel(nx, py, col);
destTex.SetPixel(px, ny, col);
destTex.SetPixel(nx, ny, col);
}//end for
}//end for
destTex.Apply();
GetComponent<SpriteRenderer>().sprite = Sprite.Create(destTex, new Rect(Camera.main.rect.x, Camera.main.rect.y, destTex.width, destTex.height), new Vector2(0.5f, 0.5f),100f);`
}//end paint
}
Your answer
Follow this Question
Related Questions
RaycastHit2D hit to texture coordinate 0 Answers
Texture Max Size Value related rule 1 Answer
Fade between two moving cameras 1 Answer