不规则按钮也太好实现了吧!(不要正式使用)

效果

ezgif.com-video-to-gif

做法

  1. 做好你的不规则按钮图片,然后加个按钮组件:

    image

  2. 给你的按钮节点加个 PolygonCollider2D,选好 Threshold 自动生成多边形:

    image

  3. 复制这段代码到你项目的任何一个 TypeScript 文件里:

    import { _decorator, PolygonCollider2D, Intersection2D, UITransform, Vec2, Mat4 } from 'cc';
    import { EDITOR_NOT_IN_PREVIEW } from 'cc/env';
    
    declare module "cc" {
        interface UITransform {
            _maskTest(worldPoint: Readonly<Vec2>): boolean;
        }
    }
    
    if (!EDITOR_NOT_IN_PREVIEW) {
        (() => {
            const vendorMaskTest = UITransform.prototype._maskTest;
            const cacheLocalPoint = new Vec2();
            const cacheMatrix = new Mat4();
            UITransform.prototype._maskTest = function(this: UITransform, ...args) {
                const [worldPoint] = args;
                const collider = this.node.getComponent(PolygonCollider2D);
                if (collider) {
                    const worldMatrix = this.node.getWorldMatrix(cacheMatrix);
                    const inverseWorldMatrix = Mat4.invert(worldMatrix, worldMatrix);
                    const localPoint = Vec2.transformMat4(cacheLocalPoint, worldPoint, inverseWorldMatrix);
                    if (!Intersection2D.pointInPolygon(localPoint, collider.points)) {
                        return false;
                    }
                }
                return vendorMaskTest.apply(this, args);
            }
        })();
    }
    
    
  4. 大功告成。

3赞

你太天真了,这种方式,几乎只会存在于demo中

没错,抛砖引玉,期待引擎早日官方支持

前段时间论坛里出了hitTest,像素级点击

不好意思,原来是队友,我的锅

实现是好实现,性能问题

mark@

来看看这个 高性能 Hittest 像素级点击反馈

9.9支持 :rofl:

GIF 2023-9-22 15-31-04

之前在项目中使用rendertexture做过,快是快就是对应的图片要多一倍

好兄弟咋实现的。?

大概就是 谁来抬我一手。。。。不行了啊 里面 copyTextureToBuffers 这个取点击位置的像素值,判定alpha,不透明的话阻止事件透传。

获取像素不难,难的是自己处理plist,自动图集,动态合图,还有散图以及 trim 模式,我的组件全部支持了

而且我很怀疑楼上说的高性能,因为都是读取像素,没啥比其他人高的,我的组件也都对像素做了缓存,有需要的可以看看