一,前景
1,点击区域不是一个矩形,如下图所示
二,新建一个节点(Node)
1,添加Sprite组件
2,继续添加Button组件
3, 添加PolygonCollider2D组件
三,核心代码
import {
_decorator,
Component,
Node,
isValid,
PolygonCollider2D,
Intersection2D,
UITransform,
Vec3,
v2,
EventTouch,
math,
v3,
Sprite, SpriteFrame, ImageAsset
} from 'cc';
import IBundleResItemType from "../manager/bundle/IBundleResItemType";
import AppUtil from "../utils/AppUtil";
import { ResConfig } from "../manager/bundle/ResConfig";
import BundleResManager from "../manager/bundle/BundleResManager";
const { ccclass, property } = _decorator;
@ccclass('ButtonUI')
export class ButtonUI extends Component {
@property({ type: Node, tooltip: "按钮" })
private btnImg: Node = null;
protected start(): void {
const item: IBundleResItemType<ImageAsset> = AppUtil.getPreload(ResConfig, "red") as IBundleResItemType<ImageAsset>;
let imageAsset: ImageAsset = BundleResManager.instance.getAsset(AppUtil.getLoadingABName(ResConfig), item.urls as string);
this.btnImg.getComponent(Sprite).spriteFrame = SpriteFrame.createWithImage(imageAsset);
}
protected onEnable(): void {
this.listener(true);
}
protected onDisable(): void {
this.listener(false);
}
private listener(isAdd: boolean): void {
if (isAdd) {
this.btnImg.on(Node.EventType.TOUCH_END, this.onClickHandler, this);
} else {
this.btnImg.off(Node.EventType.TOUCH_END, this.onClickHandler, this);
}
}
private onClickHandler(event: EventTouch): void {
if (!isValid(this.node)) return;
if (this.isCheckAreaSuccess(this.btnImg, event)) {
console.log("点击成功");
} else {
console.log("点击失败");
}
}
private isCheckAreaSuccess(btnNode: Node, event: EventTouch): boolean {
if (!isValid(btnNode) || !event) {
return false;
}
let collider: PolygonCollider2D = btnNode.getComponent(PolygonCollider2D);
let mathV2: math.Vec2 = event.getUILocation();
let local: Vec3 = btnNode.getComponent(UITransform).convertToNodeSpaceAR(v3(mathV2.x, mathV2.y));
return Intersection2D.pointInPolygon(v2(local.x, local.y), collider.points);
}
}