如何获取当前鼠标指针下的像素颜色

时间:2015-09-21 09:50:17

标签: unity3d unity3d-2dtools unity5

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

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

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);
}

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

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

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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;
    }
}