You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity颜色选择器光标位置偏移致取色错误问题求助

颜色选择器光标位置异常的修复方案

你的取色逻辑存在几个关键的坐标系转换错误,导致实际取到的颜色和点击位置不匹配,以下是具体的修复方案:

问题根源

  1. 坐标系不匹配:直接用Rect.position(世界空间位置)和Input.mousePosition(屏幕空间坐标)相减,无法得到正确的UI局部坐标,忽略了UI的锚点、Pivot和缩放参数影响。
  2. Y轴方向颠倒:屏幕坐标系Y轴向上,而Texture2D的像素坐标系默认Y轴向下,未做翻转处理。
  3. 比例计算错误:原代码中计算Y轴像素坐标时误用了ColorTexture.width,应该对应ColorTexture.height。
  4. 无边界校验:点击超出颜色选择器区域时,会导致取色坐标超出纹理范围,引发报错。

修复后的完整代码

public RectTransform ColorPickerRect;
public Text TestText;
public Texture2D ColorTexture;
public GameObject Plane;

public void PickColor()
{
    // 将屏幕鼠标位置转换为RectTransform的局部坐标,自动处理UI缩放、锚点
    if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
        ColorPickerRect, 
        Input.mousePosition, 
        null, // 若使用了UI相机,此处传入对应的Camera对象
        out Vector2 localPoint))
    {
        // 将局部坐标转换为0-1的归一化范围
        float normalizedX = (localPoint.x + ColorPickerRect.rect.width / 2) / ColorPickerRect.rect.width;
        float normalizedY = (localPoint.y + ColorPickerRect.rect.height / 2) / ColorPickerRect.rect.height;

        // 转换为纹理像素坐标,同时翻转Y轴匹配纹理坐标系
        int pixelX = Mathf.Clamp((int)(normalizedX * ColorTexture.width), 0, ColorTexture.width - 1);
        int pixelY = Mathf.Clamp((int)((1 - normalizedY) * ColorTexture.height), 0, ColorTexture.height - 1);

        Color pickedColor = ColorTexture.GetPixel(pixelX, pixelY);
        SetActualColor(pickedColor);
    }
}

void SetActualColor(Color col)
{
    TestText.color = col;
    Plane.GetComponent<MeshRenderer>().sharedMaterial.color = col;
}

关键修复说明

  • 使用RectTransformUtility.ScreenPointToLocalPointInRectangle完成屏幕坐标到UI局部坐标的转换,自动适配UI布局参数。
  • 通过归一化坐标计算,避免直接操作原始坐标带来的偏移问题。
  • 用1 - normalizedY翻转Y轴,匹配纹理的像素坐标系方向。
  • Mathf.Clamp限制像素坐标范围,防止越界报错。

内容的提问来源于stack exchange,提问作者Joice Philip Thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 04:54:24