本文将带您了解关于cocosjs踩坑旅程之ccui.Button那点事的新内容,同时我们还将为您解释cocosjavascript的相关知识,另外,我们还将为您提供关于1cocos2dx扩展库UI控件
本文将带您了解关于cocos js 踩坑旅程 之ccui.Button 那点事的新内容,同时我们还将为您解释cocos javascript的相关知识,另外,我们还将为您提供关于1cocos2dx扩展库UI控件,CCControlSlider,CCScale9Sprite(九妹图),CCControlSwitch,CCControlButton、cocos creator Button控件用法、cocos creator基础-(七)cc.Button使用、以及不规则按钮区域的实现、Cocos CSLoader Button的实用信息。
本文目录一览:- cocos js 踩坑旅程 之ccui.Button 那点事(cocos javascript)
- 1cocos2dx扩展库UI控件,CCControlSlider,CCScale9Sprite(九妹图),CCControlSwitch,CCControlButton
- cocos creator Button控件用法
- cocos creator基础-(七)cc.Button使用、以及不规则按钮区域的实现
- Cocos CSLoader Button
cocos js 踩坑旅程 之ccui.Button 那点事(cocos javascript)
之前工作的时候一直使用的是lua脚本语言,最近刚刚接触cocos-JS发现要踩的坑还有很多,再次将我踩过的一些坑写出来。转入正题
在cocosjs中创建一个button(按钮)大体可以分为3种方法。
1.创建一个Menu。
2.使用cocostudio编辑器编辑ui界面导入到工程中通过getChildByTag(),getChildByName()获取这个button。
3.直接 new ccui.Button();
但是 会出现报错 ccui is not defined,原因就是没有引入“extensions”模块,所以需要在project.json中的 modules中添加 extensions,ex:modules:["cocos2d-x","extensions"];
修改之后就可以正常使用ccui
var btn_close= new ccui.Button(res.Btn_close_normal,res.Btn_close_selected); //btn_close.loadTexturedisabled(res.HelloWorld_png); //设置导入资源true //btn_close.loadTexturenormal(res.HelloWorld_png); //btn_close.setTouchEnabled(false);设置按钮能否点击 //btn_close.setScale9Enabled(true);//设置按钮能否进行scale9缩放,需要设置按钮的尺寸 btn_close.setPosition(size.width/2,size.height/2); btn_close.setpressedActionEnabled(false);//设置是否伴随点击缩放按钮图片 btn_close.setTitleText("Title Button");//在按钮上方添加一个label. //btn_close.setContentSize(cc.size(150,48)); //btn_close.addTouchEventListener(this.touchEvent,this)<p> </p> btn_close.addClickEventListener cc.MenuItem (function (sender,type) { cc.log("哈哈哈111"); if(type==ccui.Widget.TOUCH_BEGAN) { cc.log("哈哈哈"); } },this); this.addChild(btn_close);
通过ccuix.Button 创建的btn,存在两种触发点击事件的方法
addClickEventListener(只在按钮点击触发一次),addTouchEventListener(按钮点击 抬起 移动 取消状态触发事件)
<pre name="code">touchEvent: function (sender,type) { switch (type) { case ccui.Widget.TOUCH_BEGAN: cc.log("Touch Down"); break; case ccui.Widget.TOUCH_MOVED: cc.log("Touch Move"); break; case ccui.Widget.TOUCH_ENDED: cc.log("Touch Up"); break; case ccui.Widget.TOUCH_CANCELED: cc.log("Touch Cancelled"); break; default: break; } }
1cocos2dx扩展库UI控件,CCControlSlider,CCScale9Sprite(九妹图),CCControlSwitch,CCControlButton
-
UI控件来自cocos2dx的扩展库,完善了UI方面的元素,使cocos2dx更加丰富多彩。使用扩展库需包含:
#include “cocos-ext.h” USING_NS_CC_EXT; |
- CCControlSlider
CCControlSlider * slider = CCControlSlider::create(“sliderTrack.png”,”sliderProgress.png”,”sliderThumb.png”); |
第一个参数表示,slider滑动的轨道,即背景色。第二个参数表示滑动的进度。第三个参数表示拖动的按钮。
slider->setMaximumValue(2.0f); //设置滑动最大值 slider->setMinimumValue(0.0f); //设置滑动最小值
slider->setValue(0.5f); //设置默认值 slider->setMaximumAllowedValue(1.2f); //设置某一个范围内的最大值 slider->setMinimumAllowedValue(0.3f); //设置某一个范围内的最小值 |
slider->addTargetWithActionForControlEvents(this, cccontrol_selector(T12UI::controlCallback), CCControlEventValueChanged); |
设置事件的响应函数
typedef unsigned int CCControlEvent; typedef void (CCObject::*SEL_CCControlHandler)(CCObject*,CCControlEvent); #define cccontrol_selector(_SELECTOR)(SEL_CCControlHandler)(&_SELECTOR); |
关于CCControlEvent
/** Kinds of possible events for the control objects. */ enum { CCControlEventTouchDown = 1 << 0, // A touch-down event in the control. CCControlEventTouchDragInside = 1 << 1, // An event where a finger is dragged inside the bounds of the control. CCControlEventTouchDragOutside = 1 << 2, // An event where a finger is dragged just outside the bounds of the control. CCControlEventTouchdragenter = 1 << 3, // An event where a finger is dragged into the bounds of the control. CCControlEventTouchDragExit = 1 << 4, // An event where a finger is dragged from within a control to outside its bounds. CCControlEventTouchUpInside = 1 << 5, // A touch-up event in the control where the finger is inside the bounds of the control. CCControlEventTouchUpOutside = 1 << 6, // A touch-up event in the control where the finger is outside the bounds of the control. CCControlEventTouchCancel = 1 << 7, // A system event canceling the current touches for the control. CCControlEventValueChanged = 1 << 8 // A touch dragging or otherwise manipulating a control,causing it to emit a series of different values. }; typedef unsigned int CCControlEvent; |
- slider案例说明:
T12UI.h |
#ifndef __T12UI_H__ #define __T12UI_H__
#include "cocos2d.h" #include "TBack.h" #include "cocos-ext.h" USING_NS_CC; USING_NS_CC_EXT;
class T12UI :public TBack { public: static CCScene * scene(); CREATE_FUNC(T12UI); bool init();
cclabelAtlas * atlas;
//slider的回调函数 void sliderCallBack(CCObject* sender,CCControlEvent event); };
#endif |
T12UI.cpp |
#include "T12UI.h" #include "AppMacros.h" #include "SimpleAudioEngine.h" using namespace CocosDenshion;
CCScene *T12UI::scene() { scene = CCScene::create(); T12UI * layer = create(); scene->addChild(layer); return scene; }
//UI控件来自cocos2dx的扩展库,完善了UI方面的元素,使cocos2dx更加丰富多彩。使用扩展库需要包含 bool init() { TBack::init();
//第一个参数表示slider滑动的轨道,即背景色。第二个参数表示滑动的进度。 //第三个参数表示拖动的按钮 CCControlSlider *slider = CCControlSlider::create("sliderTrack.png","sliderProgress.png",21); font-family:新宋体; font-size:9.5pt">"sliderThumb.png");
//设置滑动最大值 slider->setMaximumValue(2.0f); //设置滑动的最小值 slider->setMinimumValue(0.0f);
//设置默认值 slider->setValue(0.5f); //设置某一范围内的最大值,当移动到了1.2之后移动不了了 slider->setMaximumAllowedValue(1.2f); //设置某一范围内的最小值,向左移动到0.3之后移动不了了 slider->setMinimumAllowedValue(0.3f); //设置slider的所在位置 slider->setPosition(ccp(winSize.width / 2,winSize.height/2 - 30));
slider->addTargetWithActionForControlEvents( this, cccontrol_selector(sliderCallBack),138); font-family:新宋体; font-size:9.5pt">CCControlEventValueChanged);
CCString *str = CCString::createWithFormat("%.2g",slider->getValue()); //第一个参数表示要显示的字符串 //第二个参数表示从哪张图片中取值 //第三个参数表示的是每个字的宽度width //第四个参数表示的是每个字的高度 //第五个参数表示的是起始的字符 /* creates the cclabelAtlas with a string,a char map file(the atlas), the width and height of each element and the starting char of the atlas */ atlas = cclabelAtlas::create( str->getCString(), "fonts/fps_images.png", 12,32,21); font-family:新宋体; font-size:9.5pt">'.'); atlas->setAnchorPoint(ccp(0.5,0.5)); //设置字体的放大效果 atlas->setScale(2.0f); atlas->winSize.height / 2 + 30)); addChild(atlas);
slider->setValue(1.3f);
addChild(slider);
return true; }
//设置slider的回调函数 //这里的sender表示发送的一者 void CCControlEvent event) { CCControlSlider * slider = (CCControlSlider *)sender;
getValue()); //因为成为了全局的了,所以能够访问的到 atlas->setString(str->getCString()); } |
运行结果: 最大值
最小范围:
最大范围: 运行结果在0.3和1.2之间 |
- CCControlSwitch
第一个参数,掩底背景图片,第二个参数为开的图片,第三个参数为关的图片,第四个参数为手指划到按钮,第五,六个参数分别为开和关显示的文字。
CCControlSwitch * sw = CCControlSwitch::create( CCSprite::create("switch-mask.png"), CCSprite::create("switch-on.png"), CCSprite::create("switch-off.png"), CCSprite::create("switch-thumb.png"), cclabelTTF::create("ON","Courier New",20), cclabelTTF::create("OFF",20) ); |
设置时间触发后的响应函数
sw->addTargetWithActionForControlEvents(this,cccontrol_selector(T12UI::switchCallback), CCControlEventValueChanged) |
如何在响应函数中获取选项
void T12UI::switchCallback(CCObject * sender,CCControlEvent event) { CCControlSwitch * sw = (CCControlSwitch *)sender; If(sw->isOn()) { cclog(“On”); } else { cclog(“off”); } } |
5 CCControlSwitch案例说明
T12UI.h |
init();
//开关的回调函数 void switchCallBack(init();
//通过SimpleAudioEngine的方式实现加载音乐 SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic("audio/start.wav"); //创建开关、 //第一个参数为:掩底背景CCSprite //第二个参数为开的CCSprite //第三个参数为关的CCSprite //第四个参数为手指滑到CCSprite //第五个参数on的label //第六个参数为off的label CCControlSwitch *sw = CCControlSwitch::create( CCSprite::"switch-mask.png"), "switch-on.png"),21); font-family:新宋体; font-size:9.5pt">"switch-off.png"),21); font-family:新宋体; font-size:9.5pt">"switch-thumb.png"),133); font-family:新宋体; font-size:9.5pt">cclabelTTF::"ON",21); font-family:新宋体; font-size:9.5pt">"Courier New",21); font-family:新宋体; font-size:9.5pt">"OFF",20) ); //设置开关的位置 sw->winSize.height / 2)); sw->addTargetWithActionForControlEvents(this,0); font-family:新宋体; font-size:9.5pt">switchCallBack),138); font-family:新宋体; font-size:9.5pt">CCControlEventValueChanged);
//设置开关默认是关闭的 sw->seton(false); //将开关添加到Layer中去 addChild(sw);
return true; }
//开关的回调函数 void CCControlSwitch * sw = (CCControlSwitch *)sender; if (sw->isOn()) { cclog("click On"); //通过playBackgroundMusic打开音乐 playBackgroundMusic("audio/start.wav"); } else { //通过stopBackgroundMusic()关闭音乐 stopBackgroundMusic("audio/start.wav"); "click off"); } } |
运行结果:
|
- CCScale9Sprite九妹图
CCScale9Sprite对象,是一种CCSprite对象的变形,它的用法和CCSprite类似,不同点是:CCScale9Sprite对象有个特性就是缩放贴图时可以尽量不失帧。比如QQ聊天内边框
原理:
CCScale9Sprite的实现非常巧妙,是通过1个CCSpriteBatchNode和9个CCSprite来实现的,原理很简单,通过将原纹理资源切割成9部分(PS:这也是叫九宫图的原因)。根据想要的尺寸,完成以下三个步骤:
- 保持4个角部分不变形
-
单向拉伸4条边(即在4个角两两之间的边,比如上边,只做横向拉伸)
- 双向拉伸中间部分(即九宫图的中间部分,横向,纵向同时拉伸,PS:拉伸比例不一定相同)
CCSpriteBatchNode的资源为整个的纹理,9 个CCSprite 对应于纹理的9
个部分(根据纹理不同,9 部分所占比例会有所不同),根据想要的尺寸,
将9 部分拼装在一起!
- 需要包含的头文件
#include “cocos-ext.h” //包含cocos-ext.h头文件
using namespace cocos2d::extension; //引用cocos2d::extension 命名空间
使用说明:
CCScale9Sprite::create(const char* file,CCRect rect,CCRect,capInsets);
第一个参数为文件,第二个参数使用文件的大小,第三个参数如下,若未设置,或设置图分别如下:
我们知道CCSprite的拉伸方式是通过setScale();来实现的,而对于CCScale9Sprite则不同。它是通过setContentSize(constCCSize & size);来实现图片的拉伸。
测试代码:
CCScale9Sprite * spr = CCScale9Sprite::create("scale9.png",CCRectMake(0,116,102),CCRectMake(40,30,40)); spr->setPosition(ccp(winSize.width/2,winSize.height/2)); addChild(spr); //spr->setScale(4.0f); spr->setPreferredSize(CCSizeMake(400,200)); |
关于CCScale9Sprite::create()
T12UI.h |
init(); };
#endif |
CCScale9Sprite * s9spr = CCScale9Sprite::create( "scale9.png",138); font-family:新宋体; font-size:9.5pt">CCRectMake(0,138); font-family:新宋体; font-size:9.5pt">CCRectMake(30,40,56,20)); s9spr->winSize.height / 2)); addChild(s9spr); s9spr->setPreferredSize(CCSize(500,100)); return true; } |
运行结果:
|
- CControlButton
CCScale9Sprite * bgbutton = CCScale9Sprite::create("button.png"); //背景色图片 CCScale9Sprite * bgbuttonlighted = CCScale9Sprite::create("buttonHighlighted.png"); //背景色高亮图片 cclabelTTF * titlebutton = cclabelTTF::create("Touch Me","Courier New",30); //按钮的文本 CCControlButton * button = CCControlButton::create(titlebutton,bgbutton); //创建按钮 button->setColor(ccc3(159,168,176)); //调色 button->setBackgroundSpriteForState(bgbuttonlighted, CCControlStateHighlighted); //按下后背景高亮 button->setTitleColorForState(ccwHITE, CCControlStateHighlighted); //按下后文本高亮 button->addTargetWithActionForControlEvents(this,cccontrol_selector(T12UI::buttonTouchDown)); button->addTargetWithActionForControlEvents(this,cccontrol_selector(T12UI::buttonTouchDown),CCControlEventTouchDown); button->addTargetWithActionForControlEvents(this,cccontrol_selector(T12UI::buttonTouchDragInside),CCControlEventTouchDragInside); |
响应的事件类型如下:
/** Kinds of possible events for the control objects. */ enum {
}; typedef unsigned int CCControlEvent; |
T12UI.h |
init();
void touchDownCallBack(CCControlEvent event); void touchDragInsideCallBack(scene; }
bool init(); CCScale9Sprite *bgButton = "button.png"); CCScale9Sprite *bgButtonLighted = "buttonHighlighted.png"); cclabelTTF * text = "Touch Me",21); font-family:新宋体; font-size:9.5pt">"Couier New",50);
CCControlButton * button = CCControlButton::create(text,bgButton); //为按钮添加位置 button->winSize.height / 2)); button->setBackgroundSpriteForState(bgButtonLighted,138); font-family:新宋体; font-size:9.5pt">CCControlStateHighlighted); button->setTitleColorForState(ccRED,138); font-family:新宋体; font-size:9.5pt">CCControlStateHighlighted); addChild(button);
//为按钮添加监听事件,添加的是按钮被点击的事件 button->touchDownCallBack),138); font-family:新宋体; font-size:9.5pt">CCControlEventTouchDown); //为按钮添加监听事件,添加的是按钮Drag的事件 button->touchDragInsideCallBack),138); font-family:新宋体; font-size:9.5pt">CCControlEventTouchDragInside);
return true; }
void CCControlEvent event) { "touchDownCallBack"); }
void "touchDragInsideCallBack"); } |
运行结果:
|
cocos creator Button控件用法
Button控件用法比较简单,从控件库拖拽Button控件到场景编辑器中,我们看到Button里自带了一个label,我们不用的话,就直接将其删除即可。
选中Button控件,在右侧的属性检查器中,可以查看Button的组件属性
选择相对应的图片,然后在事件这里选择带有脚本的节点,第二个是选择脚本文件,第三个是选择这个脚本里所对应的函数,当点击这个按钮的时候,在这个函数里处理逻辑就可以了。
当然,如果我们需要处理更加细致的问题,比如按下按钮执行函数(此时不松开),那么就需要在相应的脚本文件中进行触摸事件,比如:
在脚本文件中,增加按钮属性:button : { default: null,type: cc.Button},
然后在onLoad函数中,进行按钮的注册:
var self = this;
self.button.node.on(cc.Node.EventType.TOUCH_START,function(event){
console.log("按钮按下")
});
self.button.node.on(cc.Node.EventType.TOUCH_MOVE,function(event){
console.log("在按钮上滑动")
});
其他的就不一一列举了。注意一点就行,这里一定要用self,因为注册里的this代表的就不是这个this了。
cocos creator基础-(七)cc.Button使用、以及不规则按钮区域的实现
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);
}
}
});
Cocos CSLoader Button
Node* node = CSLoader::createNode("home.csb");
this->addChild(node);
Button* btnPlay = dynamic_cast<Button*>(node ->getChildByName("btnPlay"));
Button* btnPlay = static_cast<ui::Button*>(Helper::seekWidgetByName(node, "btnPlay"));
btnPlay ->addClickEventListener(CC_CALLBACK_1(XXX::onPlay, this));
btnPlay->addTouchEventListener(CC_CALLBACK_2(XXX::onPlay, this));
void XXX::onPlay(Ref *pSender, Widget::TouchEventType type)
{
switch (type)
{
case Widget::TouchEventType::BEGAN:
break;
case Widget::TouchEventType::MOVED:
break;
case Widget::TouchEventType::ENDED:
break;
case Widget::TouchEventType::CANCELED:
break;
default:
break;
}
}
void XXX::onPlay(Ref* sender)
{
}
关于cocos js 踩坑旅程 之ccui.Button 那点事和cocos javascript的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于1cocos2dx扩展库UI控件,CCControlSlider,CCScale9Sprite(九妹图),CCControlSwitch,CCControlButton、cocos creator Button控件用法、cocos creator基础-(七)cc.Button使用、以及不规则按钮区域的实现、Cocos CSLoader Button的相关信息,请在本站寻找。
本文标签: