I am making a game where there is a color picker to change the color of an GameObject where clicking on a color in the button should take back the color it points though inside the buttons and pass it to the material of the game object. It mostly works fine but there is some issue with the cursor position which brings in a different color, but not the color to which it is pointed. Requesting help.
public RectTransform Rect;
public Text TestText;
public Texture2D ColorTexture;
public GameObject Plane;
public void PickColor()
{
Vector3 imagePos = Rect.position;
float globalPosX = Input.mousePosition.x - imagePos.x;
float globalPosY = Input.mousePosition.y - imagePos.y;
int localPosX = (int)(globalPosX * (ColorTexture.width / Rect.rect.width));
int localPosY = (int)(globalPosY * (ColorTexture.height / Rect.rect.height));
float x = Input.mousePosition.x * (ColorTexture.width / Rect.rect.width);
float y = Input.mousePosition.y * (ColorTexture.width / Rect.rect.width);
Color Col = ColorTexture.GetPixel(localPosX, localPosY);
TestText.color = Col;
SetActualColor(Col);
}
void SetActualColor(Color Col)
{
TestText.color = Col;
Plane.GetComponent<MeshRenderer>().sharedMaterial.color = Col;
}
CodePudding user response:
RectTransform.rect.width
and RectTransform.rect.height
aren't actually in screen size pixels as opposed to Input.mousePosition
.`They are scaled with the canvace/screen, so that you always get a significant error with your correct formula.
You need to determine the global position of the corners and calculate the dimensions from that. Luckily there is a build in function for that.
Vector3[] corners = new Vector3[4];
Rect.GetWorldCorners(corners);
Vector2 dimensions = corners[2] - corners[0];
int localPosX = (int)(globalPosX * (ColorTexture.width / dimensions.x));
int localPosY = (int)(globalPosY * (ColorTexture.height / dimensions.y));
You also need to make sure that the pivot of the rect
is set to (0,0) since the texture coordinates start from the bottom left.