cc.Class({ extends: cc.Component, properties: { // foo: { // default: null, // The default value will be used only when the component attaching // to a node for the first time // url: cc.Texture2D, // optional, default is typeof default // serializable: true, // optional, default is true // visible: true, // optional, default is true // displayName: 'Foo', // optional // readonly: false, // optional, default is false // }, // ... // 直接在编辑器里面绑定 button: { type: cc.Button, // default: null, }, }, // use this for initialization onLoad: function () { // 获取button组件 this.start_button = this.node.getChildByName("ks_up").getComponent(cc.Button); // 添加button组件 this.red_button = this.node.getChildByName("red_button").addComponent(cc.Button); // 添加一个响应函数 var click_event = new cc.Component.EventHandler(); click_event.target = this.node; click_event.component = "game_scene"; click_event.handler = "on_red_button_click"; click_event.customEventData = "red_button_data_77777"; // this.red_button.clickEvents = [click_event]; this.red_button.clickEvents.push(click_event); // end // 代码触发按钮的响应事件,而不用自己去触摸 this.scheduleOnce(function() { var click_events = this.red_button.clickEvents; for(var i = 0; i < click_events.length; i ++) { var comp_env_handle = click_events[i]; // 在代码里面触发按钮的响应函数 comp_env_handle.emit(["", "red_button_data_77777"]); } }.bind(this), 3); // end }, on_red_button_click: function(e, custom) { console.log("on_red_button_click: ", custom); }, // 关卡按钮1-10, 第几关 // e 本次触摸的触摸事件 // customEventData is String; on_button_click: function(e, level) { level = parseInt(level); console.log("on_button_click called:", level); }, // called every frame, uncomment this function to activate update callback // update: function (dt) { // }, });
实现不规则的按钮点击区域(copy大佬的方法重写_hittest,方便好用)
参考链接 http://blog.zovew.com/2018/03/18/Cocos-Creator不规则触摸点击实现/
可以利用PolygonCollider组件实现一个不规则碰撞的方法。
- Node节点需要添加cc.PolygonCollider,否则按原函数处理
- 获取cc.PolygonCollider组件,检测碰撞。触摸点坐标需要转NodeSpace,并且Anchor为(0.5,0.5)即:节点中心为原点
核心代码
cc.Class({ extends: cc.Component, editor: CC_EDITOR && { menu: 'i18n:Component/PolygonHitTest', }, properties: { }, /** * 加载 */ onLoad() { this.node._oldHitTest = this.node._hitTest.bind(this.node); this.node._hitTest = this.polygonHitTest.bind(this.node); }, /** * 不规则多边形触摸测试 * @param {触摸点} point * @param {监听} listener */ polygonHitTest(point, listener) { var polygonCollider = this.getComponent(cc.PolygonCollider); if (polygonCollider) { point = this.convertToNodeSpace(point); point.x -= this.getContentSize().width / 2; point.y -= this.getContentSize().height / 2; return cc.Intersection.pointInPolygon(point, polygonCollider.points); } else { return this._oldHitTest(point, listener); } } });