请教大佬们,不规则按钮的点击?
查找了挺多资料,多人建议的是射线检测,但是需求的图片是动态的不能提前获得区域描边范围,所以使用透明度来检测。
参考的是皮皮案例,获取点击的像素色值,看透明度判断是否有效点击。
【难点】皮皮用2.x做的案例,我改成了3.x,但是实际效果不对劲,感觉应该是点击位置的转换到图片不对,希望大家指点
点击:
主要的获取事件:
/**点击建筑物餐厅
* @id 携带一个餐厅编号 0-4 */
private clickLevelMap(evt: EventTouch, id) {
// this.testPosClick(id);
Log.warn(id, "?clickLevelMap>点击建筑物餐厅>>>>>>>", evt.touch.getLocation())
const img: Sprite = evt.target.getComponent(Sprite);
if (img) {
const TargetNode: Node = evt.target;
const nodeUit = TargetNode.getComponent(UITransform);
// 点击位置
const touchPos = evt.getLocation()
// 获取像素数据
const pixelsData = RenderUtil.readPixels(img.spriteFrame.texture);
// 截取像素颜色
let x = touchPos.x + nodeUit.anchorX * nodeUit.width,
y = -(touchPos.y - nodeUit.anchorY * nodeUit.height);
const index = (nodeUit.width * 4 * Math.floor(touchPos.y)) + (4 * Math.floor(touchPos.x)),
colors = pixelsData.slice(index, index + 4);
// 当前点击像素颜色
const color = new Color(colors[0], colors[1], colors[2]);
const opacity = colors[3];
Log.log("----截取像素颜色---4----------colors--------", x, ", ", y, colors)
Log.log("----截取像素颜色---3----------index--------", index, color, opacity)
}
}
/**
* 读取渲染纹理像素信息
* @param texture
* @param filpY 是否翻转Y轴,默认true
*/
public static readPixels(texture: __private._cocos_asset_assets_texture_base__TextureBase, filpY?: boolean): Uint8Array {
// 通用版本
var { width, height } = texture, gfxTexture = texture.getGFXTexture(), gfxDevice = texture['_getGFXDevice'](), bufferViews = [],
region = new gfx.BufferTextureCopy, buffer = new Uint8Array(width * height * 4);
// region.texOffset.x = region.texOffset.y = 0;
region.texExtent.width = width;
region.texExtent.height = height;
bufferViews.push(buffer);
gfxDevice?.copyTextureToBuffers(gfxTexture, bufferViews, [region]);
// 翻转
if (filpY !== false) {
let i = 0, len1 = height / 2, len2 = width * 4, j: number, idx0: number, idx1: number;
while (i < len1) {
j = 0;
while (j < len2) {
idx0 = i * len2 + j;
idx1 = (height - i - 1) * len2 + j++;
[buffer[idx0], buffer[idx1]] = [buffer[idx1], buffer[idx0]];
}
i++;
}
}
return buffer;
// 3.4及以上版本,有点问题
// return texture.readPixels();
}
上传了代码:
ClickGetColor.zip (2.9 KB)