I'm trying to implement that when dragging the circle cursor on the texture, warp the texture like Fitlers/Liquify/Forward Warp Tool in photoshop.
This is the code what I implemented.
public Texture2D backgroundTexture;
private Color[] backuppixels;
public void OnMouseDownEvent(MouseDownEvent evt)
{
backuppixels = backgroundTexture.GetPixels();
}
public void OnMouseMoveEvent(MouseMoveEvent evt)
{
//some code
WarpTexture(currentposition, delta);
}
private void WarpTexture(Vector2 textmousepos, Vector2 delta)
{
Color[] pixels = backgroundTexture.GetPixels();
for (int y = 0; y < backgroundTexture.height; y++)
{
for (int x = 0; x < backgroundTexture.width; x++)
{
var distance = (new Vector2(textmousepos.x, textmousepos.y)
- new Vector2(x,y)).magnitude;
if (distance < radius)
{
int index = y * backgroundTexture.width + x;
float factor = Mathf.Pow(distance, warpStrength);
Vector2 pixelpos = new Vector2(x, y) - delta;
int pixelx = Mathf.FloorToInt(pixelpos.x);
int pixely = Mathf.FloorToInt(pixelpos.y);
pixelx = Mathf.Clamp(pixelx, 0, backgroundTexture.width - 1);
pixely = Mathf.Clamp(pixely, 0, backgroundTexture.height - 1);
int pxielindex = pixely * backgroundTexture.width + pixelx;
pixels[index] = backuppixels[pxielindex];
}
}
}
backgroundTexture.SetPixels(pixels);
backgroundTexture.Apply();
}
enter image description here This picture is what I implemented.
First, I found the pixels on the cursor. Second, when dragging set pixel colors using "delta" and "backuppixels".
It works but not warp texture smoothly like in photoshop. I think, the math formula what I used is not perfect. Any help will be appreciated.