1. cc.Button
添加按钮的方法 2种方式
(1)直接创建带Button组件的节点;
(2) 先创建节点,再添加组件;
按钮组件, 按钮是游戏中最常用的组件, 点击然后响应事件;
按钮的过渡效果:
过渡: 普通状态, 鼠标滑动到物体上, 按下状态, 禁用状态
(1)没有过渡,只有响应事件;
(2)颜色过渡, 过渡效果中使用颜色;
(3)精灵过渡,使用图片过渡;
(4)缩放过渡, 选项,在disable的时候是否置灰;
按钮禁用;
按钮添加响应事件 --> 节点-->组件 --> 代码的函数;
按钮传递自定义参数; ---> 字符串对象;
Button响应这个触摸点击,所以Button所挂的这个节点,一定要有大小,如果你向大小(0, 0)的节点上,挂一个Button,这个是无法响应点击事件;
2. 代码使用cc.Button
代码添加/获取cc.Button组件;
代码里面添加按钮的响应事件;
代码触发按钮指定的回掉函数;
Component.EventHandler
var eventHandler = new cc.Component.EventHandler();
eventHandler.target = newTarget;
eventHandler.component = "MainMenu";
eventHandler.handler = "OnClick";
eventHandler.customEventData = "my data";
eventHandler.emit(["param1", "param2", ....]);
例:game_scene.js
// Learn cc.Class:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/class.html
// - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/class.html
// Learn Attribute:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
// - [English] http://docs.cocos2d-x.org/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
// - [English] https://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html
cc.Class({
extends: cc.Component,
properties: {
// foo: {
// // ATTRIBUTES:
// default: null, // The default value will be used only when the component attaching
// // to a node for the first time
// type: cc.SpriteFrame, // optional, default is typeof default
// serializable: true, // optional, default is true
// },
// bar: {
// get () {
// return this._bar;
// },
// set (value) {
// this._bar = value;
// }
// },
//获取button 编辑器直接获取
button: {
default: null,
type: cc.Button,
},
},
// LIFE-CYCLE CALLBACKS:
onLoad () {
//获取button 代码获取
this.my_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_custom_data77777777777";
// 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(["", "auto_event_66666666666"]);
}
}, 3);
},
on_red_button_click: function(e, custom) {
console.log("on_red_button_click", custom);
},
//关卡按钮1-10, e-->触摸事件 leve-->第几关 为字符串
on_button_click: function(e, level) {
level = parseInt(level);
console.log("on_button_click call!!!", level);
},
start () {
},
// update (dt) {},
});
工程截图