效果
做法
-
做好你的不规则按钮图片,然后加个按钮组件:
-
给你的按钮节点加个
PolygonCollider2D
,选好Threshold
自动生成多边形: -
复制这段代码到你项目的任何一个 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); } })(); }
-
大功告成。