0

我想获取当前位于鼠标指针下的像素的颜色。

我想出了这段代码,但这并没有给出确切的位置,因为 Texture2d.GetPixel 不适用于浮动。这段代码确实给出了颜色,但它没有给出确切鼠标位置的颜色,因为我必须将值转换为整数,因为 Texture2D.GetPixel 无法处理浮点数

Texture2D texture;
public Color ColorBelowMouse;
public Vector3 x;

// Use this for initialization
void Start () 
{
    texture=gameObject.GetComponent<GUITexture>().texture as Texture2D;

}

// Update is called once per frame
void Update () 
{
    Debug.Log(texture.GetPixel((int) Input.mousePosition.x, (int) Input.mousePosition.y));
    ColorBelowMouse=texture.GetPixel( (int) Input.mousePosition.x, (int) Input.mousePosition.y);
}

请告诉我如何获得确切鼠标位置的颜色。

如果我的方法是错误的,请告诉我正确的方法。

4

2 回答 2

0
Vector2 pos = Input.mousePosition; 
Camera _cam = Camera.mainCamera; 
Ray ray = _cam.ScreenPointToRay(pos);
Physics.Raycast(_cam.transform.position, ray.direction, out hit, 10000.0f);
Color c;
if(hit.collider) {
    Texture2D tex = (Texture2D)hit.collider.gameObject.renderer.material.mainTexture; // Get texture of object under mouse pointer
    c = tex.GetPixelBilinear(hit.textureCoord2.x, hit.textureCoord2.y); // Get color from texture
}
于 2015-09-21T09:54:00.223 回答
0

这似乎有效!

public Texture2D ColorPalleteImage;  //Any Texture Image
public Color ColorBelowMousePointer;
public Rect ColorPanelWidthAndHeight; // set width and height appropriately

void OnGUI() 
{
    GUI.DrawTexture(ColorPanelWidthAndHeight, ColorPalleteImage);

    if (GUI.RepeatButton(ColorPanelWidthAndHeight, ColorPalleteImage))
    {
        Vector2 pickpos  = Event.current.mousePosition;

        float aaa  = pickpos.x - ColorPanelWidthAndHeight.x;

        float bbb  =  pickpos.y - ColorPanelWidthAndHeight.y;

        int aaa2  = (int)(aaa * (ColorPalleteImage.width / (ColorPanelWidthAndHeight.width + 0.0f)));

        int bbb2  =  (int)((ColorPanelWidthAndHeight.height - bbb) * (ColorPalleteImage.height / (ColorPanelWidthAndHeight.height + 0.0f)));

        Color col  = ColorPalleteImage.GetPixel(aaa2, bbb2);

        ColorBelowMousePointer= col;
    }
}
于 2015-09-21T10:20:30.253 回答