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

鼠标在Texture2D上移动时mouseX与mouseY值始终为0的问题咨询

解决Unity中RawImage上鼠标坐标始终为0的问题

问题分析

当鼠标在挂载RawImage的Texture2D上移动时,mousePos.x和mousePos.y始终返回0,核心原因多来自坐标转换的参数错误,或未正确将UI坐标映射到纹理像素坐标。

修复方案

1. 修正Canvas渲染模式对应的Camera参数

如果你的Canvas使用Screen Space - Overlay(UI默认模式),调用RectTransformUtility.ScreenPointToLocalPointInRectangle时不能传Camera.main,Overlay模式下UI无需相机,应传入null:

修改Update方法代码:

void Update()
{
    RectTransformUtility.ScreenPointToLocalPointInRectangle(rect,
        Input.mousePosition, null, out mousePos);

    print("Mouse Pos X " + mousePos.x + " Mouse Pos Y " + mousePos.y);
}

2. 转换为Texture2D的像素坐标(若需操作纹理像素)

如果你的目标是获取鼠标在纹理上的像素位置,仅获取RectTransform本地坐标不够,需要将其换算为纹理像素尺寸:

void Update()
{
    RectTransformUtility.ScreenPointToLocalPointInRectangle(rect,
        Input.mousePosition, null, out mousePos);

    // 从RectTransform本地坐标转换为纹理像素坐标
    float texturePixelX = (mousePos.x + rect.rect.width / 2) / rect.rect.width * texture2DSpriteWithClouds.width;
    float texturePixelY = (mousePos.y + rect.rect.height / 2) / rect.rect.height * texture2DSpriteWithClouds.height;

    print("Texture Pixel X: " + texturePixelX + ", Y: " + texturePixelY);
}

注:RectTransform本地坐标原点默认在pivot(中心),所以先偏移到Rect左下角,再按比例映射到纹理尺寸。

3. 检查UI交互基础设置

  • 确保RawImage组件的Raycast Target选项处于勾选状态,否则UI无法接收鼠标相关的坐标计算。
  • 确认RectTransform引用正确,可直接通过rawImage.rectTransform获取,比GetComponent<RectTransform>()更可靠:
void Start()
{
    var rawImage = GetComponent<RawImage>();
    if (rawImage == null)
    {
        Debug.LogError("当前对象未挂载RawImage组件");
        return;
    }
    rect = rawImage.rectTransform;
    texture2DSpriteWithClouds = rawImage.texture as Texture2D;
    if (texture2DSpriteWithClouds == null)
    {
        Debug.LogError("RawImage的Texture不是Texture2D类型");
        return;
    }
}

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:15:10