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

如何仅在横竖触摸指示条重叠处生成圆形触摸指示器?

如何在触摸指示条交叉处生成圆形指示器?

你现在的问题是用加法把横竖两个触摸条的颜色叠加,导致整个条都显示,但你需要的是仅在两个条重叠的区域(交叉点)显示颜色,进而做成圆形效果。我来给你拆解解决方案:

首先看你现有代码里的问题行:

float finalC = ( smoothTouchXS - smoothTouchXE ) + ( smoothTouchYS - smoothTouchYE ));

这里有两个问题:一是多了一个多余的右括号,二是用加法会把两个条的颜色全部叠加,而不是只保留重叠区域。

解决方案1:先实现交叉区域(矩形)

要只保留两个条的重叠区域,你需要把加法改成乘法。因为乘法的特性是:只有当两个因子都大于0时,结果才会大于0——刚好对应同时落在X条和Y条里的像素。

修正后的代码片段:

float touchX = u_TouchX;
float touchY = u_ResolutionX - u_TouchY;

float smoothTouchXS = smoothstep( u_ResolutionY - touchX - 300.0, u_ResolutionY- touchX, gl_FragCoord.y );
float smoothTouchXE = smoothstep( u_ResolutionY - touchX, u_ResolutionY - touchX + 300.0, gl_FragCoord.y );
float touchBarX = smoothTouchXS - smoothTouchXE; // 提取X轴指示条的透明度值

float smoothTouchYS = smoothstep( u_ResolutionX - touchY - 300.0, u_ResolutionX- touchY, gl_FragCoord.x );
float smoothTouchYE = smoothstep( u_ResolutionX - touchY, u_ResolutionX - touchY + 300.0, gl_FragCoord.x );
float touchBarY = smoothTouchYS - smoothTouchYE; // 提取Y轴指示条的透明度值

// 用乘法保留重叠区域
float finalC = touchBarX * touchBarY;

photo.r += finalC;
gl_FragColor = photo; // 注意:你原来的gl_FragCoord是笔误,应该是gl_FragColor

这样修改后,只有两个条交叉的矩形区域会显示颜色,但这还不是圆形。如果要真正的圆形指示器,推荐用下面的方法:

解决方案2:直接生成圆形指示器(更贴合需求)

既然目标是圆形,其实可以直接计算当前像素到触摸点的距离,用smoothstep做平滑边缘的圆形,同时也可以保留原来的横竖条效果(如果需要的话)。

代码示例:

float touchX = u_TouchX;
// 转换触摸Y坐标到Fragment坐标系(注意这里的转换逻辑要和你原来的保持一致)
float touchYInFrag = u_ResolutionY - u_TouchY;

// 1. 保留原来的横竖指示条(可选)
float smoothTouchXS = smoothstep( touchX - 300.0, touchX, gl_FragCoord.y );
float smoothTouchXE = smoothstep( touchX, touchX + 300.0, gl_FragCoord.y );
float touchBarX = smoothTouchXS - smoothTouchXE;

float smoothTouchYS = smoothstep( touchYInFrag - 300.0, touchYInFrag, gl_FragCoord.x );
float smoothTouchYE = smoothstep( touchYInFrag, touchYInFrag + 300.0, gl_FragCoord.x );
float touchBarY = smoothTouchYS - smoothTouchYE;

// 2. 生成圆形指示器
// 计算当前像素到触摸点的距离
float distToTouch = distance(gl_FragCoord.xy, vec2(touchX, touchYInFrag));
// smoothstep(外半径, 内半径, 距离):距离越小,值越接近1,形成平滑的圆形
float touchCircle = smoothstep(30.0, 20.0, distToTouch);

// 3. 叠加效果:可以选择只保留圆形,或者圆形+横竖条
// 只保留圆形:
photo.r += touchCircle;
// 或者圆形+横竖条:
// photo.r += touchBarX + touchBarY + touchCircle;

gl_FragColor = photo;

关键知识点解释

  • 乘法实现重叠区域:touchBarX * touchBarY 相当于逻辑上的“与”操作,只有同时满足在X条和Y条内的像素才会有颜色输出。
  • distance函数生成圆形:distance()计算两点间的欧氏距离,配合smoothstep可以做出边缘平滑的圆形,调整smoothstep的两个参数可以控制圆形的大小和边缘模糊程度。
  • 语法修正:你原来的代码里gl_FragCoord = photo.r是错误的,应该使用gl_FragColor来输出最终颜色。

内容的提问来源于stack exchange,提问作者0x29a

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:02:10