i am trying to get the pixel color under the mouse position
the code i used is giving me the correct pixel color just fine but not the correct position as you could see in the picture below and the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class get_pixel : MonoBehaviour
{
public RawImage pic;
public Text tex_mouse = null;
public Text tex2_color = null;
void Start ()
{
}
void Update ()
{
Vector2 mousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
int pos1 = (int)mousePosition.x;
int pos2 = (int)mousePosition.y;
Color32 color = (pic.texture as Texture2D).GetPixel(pos1, pos2);
tex_mouse.text = "x = " + pos1 + " | " + "y = " + pos2;
tex2_color.text = color.ToString();
}
}
as you can see the mouse is already in the black but it still give me the pixel color as blue
so i want it to give me the pixel color at the mouse position
@mohaned1001
What your code is actually telling Unity to do is to match the x position of the mouse with that many pixels over to the right on the image and the y position of the mouse with that many pixels up on the image. You are not returning where the mouse is over the image.
For your code to work the way it is your image must be at the bottom left corner of the screen. Like the images I have included below. The texture in the screenshots below is 256x256. I’ve used your code exactly.
GetPixels starting position (0,0) is the bottom left of the image. For the mouse position to line up on the image with your code your image must be at the bottom left of the screen.
Your thinking in trying to solve the problem is correct. However, Unity is doing the math differently. Mouse position 0,0 on the screen, with games made with Unity, is actually the very center of the screen.
I think this link elsewhere in the Unity forums may be useful.: https://forum.unity.com/threads/get-color-of-texture-under-mouse-position.103500/
I needed a script that reads a pixel regardless of the resolution of the image. Here, use it!
I needed a script that reads a pixel regardless of the resolution of the image. Here, use it!
Vector3[] corners = new Vector3[4];
Image image = GetComponent<Image>();
image.rectTransform.GetWorldCorners(corners);
Rect newRect = new Rect(corners[0], corners[2]-corners[0]);
if (newRect.Contains(Input.mousePosition))
{
Vector2 size = new Vector2( 822, 512);
Vector2 pixelCoord = Input.mousePosition-corners[0];
pixelCoord /= image.rectTransform.rect.size;
pixelCoord *= size;
Color colorPixel=image.sprite.texture.GetPixel((int)pixelCoord.x, (int)pixelCoord.y);
}