cocostudio登录界面和按钮回调的实现,JS & C++

来源:互联网 发布:055级驱逐舰 知乎 编辑:程序博客网 时间:2024/05/15 20:54

JS

1.终端创建js项目

2.用webstrom或cocos code ide打开工程文件
--用webstrom添加json文件时浏览器显示ccs没有定义,不知道是为什么,所以用cocos code ide来编写代码,再用webstrom打开就可以了
3.将打包好的json文件res目录下的所有文件拷贝到项目res目录下,   js加载不了csb文件 所以打包时需要设置成json
  在新项目中进行资源注册(resouces) Login.json or MainScene.json

4.代码如下       

        button:null,
textFiled:null,
textFiled1:null

//加载json文件  
var login = ccs.load(res.MainScene.json);
this.addChild(login.node);

//获取按钮和文本框  背景层tag为92  login的tag为93  logout的tag为94
//用户名面板(panel)tag95 输入框98   密码面板(panel1)tag99 输入框102
var img = ccui.helper.seekWidgetByTag(login.node,92);
button = ccui.helper.seekWidgetByTag(img,93);   //获取登陆按钮
button.addTouchEventListener(this.touchEvent,this);  //绑定按钮回调事件  touchEvent为定义的回调函数

var panel = ccui.helper.seekWidgetByTag(login.node,95);
textFiled = ccui.helper.seekWidgetByTag(panel,98);  //获取用户名文本框

var panel1 = ccui.helper.seekWidgetByTag(login.node,99);
textFiled1 = ccui.helper.seekWidgetByTag(panel1,102);  //获取密码文本框

//回调函数  写在构造函数的外面
touchEvent:function(){
switch(sender,type){
case ccui.Widget.TOUCH_BEGAN:     //按下按钮
break;

        case ccui.Widget.TOUCH_MOVED:     //移动
break;

        case ccui.Widget.TOUCH_ENDED:     //点击结束
        var name = textFiled.getString();
        var password = textFiled1.getString();
        if (name == "zhangcindy" && password == "hehe"){
         alert("登录成功");
         cc.director.runScene(new GameScene());
      }else {
      alert("用户名或密码错误");
      }
      break;

    case ccui.Widget.CANCELED:    //取消按钮  按下之后移开了  不是在按钮上结束点击的
         alert("取消登录");
         break;
      default:
      break;

}
}

-------------------------------------------------------------------------------------------------

c++加载cocostudio打包生成的csb文件
//头文件
#include "cocostudio/cocostudio.h"
#include "ui/cocosgui.h"
#include <string>
using namespace cocostudio;
using namespace ui;

//全局变量
TextField * userName;
TextField * userPass;

//加载csb文件
auto node = CSLoader::getInstance()->createNode("Login.csb");
node->setTag(1);
addChild(node);

//获取按钮
//auto不知道要生成什么类型,所以要强制转换(Button*)成Button型
auto button = (Button*)node->getChildByTag(92)->getChildByTag(93);
button->addTouchEventListener(CC_CALLBACK_2(HelloWorld::menuCloseCallback,this));//绑定事件
//获取用户名和密码的两个框
userName = (TextField*)node->getChildByTag(95)->getChildByTag(98);
userPass = (TextField*)node->getChildByTag(99)->getChildByTag(102);

//回调函数
void HelloWorld::menuCloseCallback(Ref* obj,Widget::TouchEventType t){
  switch(t){
  case Widget::TouchEventType:ENDED:{
  if (userName == "admin" && userPass == "admin"){
     MessageBox("登录成功","登录结果");
     //Director::getInstance()->replaceScene(GameScene::createScene());
  }else{
     MessageBox("用户名或密码错误","登录结果");
        }
     }
   }
}

1 0