Cocos2dx-jsb 3.x 精灵构建过程浅析:

来源:互联网 发布:hp1536设置网络打印机 编辑:程序博客网 时间:2024/05/03 14:43

Cocos2dx-jsb 3.x 精灵构建过程浅析:

1、          我们在使用精灵是一般类似于下面这样:

this.sprite= new cc.Sprite(res.HelloWorld_png);
this.addChild(this.sprite,0);

我们知道这样用,但是调用过程是怎样的呢?

2、调用过程:

会先调用C++端的:

booljs_cocos2dx_Sprite_constructor(JSContext *cx, uint32_t argc, jsval *vp)

{

    JS::CallArgs args =JS::CallArgsFromVp(argc, vp);

    bool ok = true; //创建了C++中精灵对象

    cocos2d::Sprite* cobj = new (std::nothrow)cocos2d::Sprite();

    cocos2d::Ref *_ccobj =dynamic_cast<cocos2d::Ref *>(cobj);

    if (_ccobj) {

        _ccobj->autorelease();

    }

    //JSObject *obj = JS_NewObject(cx, typeClass->jsclass, typeClass->proto,typeClass->parentProto);

    JS::RootedObject proto(cx,typeClass->proto.get());

    JS::RootedObject parent(cx,typeClass->parentProto.get());

    JS::RootedObject obj(cx, JS_NewObject(cx,typeClass->jsclass, proto, parent));

    args.rval().set(OBJECT_TO_JSVAL(obj));

    // link the native object with thejavascript object 把C++ 和javascrip中的对象绑定,具体不太清楚

    js_proxy_t* p = jsb_new_proxy(cobj, obj);

AddNamedObjectRoot(cx, &p->obj,"cocos2d::Sprite");

//调用_ctor方法,这个方法在哪里呢?在cocos提供的script文件夹下有个jsb_create_apis.js文件,这里面有我们需要的函数:

    if (JS_HasProperty(cx, obj,"_ctor", &ok) && ok)

       ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(obj),"_ctor", args);

    return true;

}

 

3、下面这段,就是有关精灵调用的部分,看到了吧,这个函数,会根据创建精灵时传入

newcc.Sprite(res.HelloWorld_png);的参数,调用不同的initXXXX方法,

/************************  Sprite *************************/

 

//这里有一点还没搞明白,就是fileName, rect这个参数怎么从C++端传到JavaScript端的,后面在研究。

_p =cc.Sprite.prototype;

_p._ctor =function(fileName, rect) {

    if (fileName === undefined) {

        cc.Sprite.prototype.init.call(this);

    }

    else if (typeof(fileName) ==="string") {

        if (fileName[0] === "#") {

            //init with a sprite frame name

            var frameName = fileName.substr(1,fileName.length - 1);

           this.initWithSpriteFrameName(frameName);

        } else {

            // Create with filename and rect

            rect ? this.initWithFile(fileName,rect) : this.initWithFile(fileName);

        }

    }

    else if (typeof(fileName) ==="object") {

        if (fileName instanceof cc.Texture2D) {

            //init with texture and rect

            rect ?this.initWithTexture(fileName, rect) : this.initWithTexture(fileName);

        } else if (fileName instanceofcc.SpriteFrame) {

            //init with a sprite frame

            this.initWithSpriteFrame(fileName);

        }

    }

};

总:其他很多类也是通过这种方法处理的,流程跟这个差不多。

参考文章:http://www.cocos2d-x.org/docs/manual/framework/html5/v3/inheritance/zh

0 0