cocos2d-xcocos2d-html5

Cocos HTML 5, Animating Sprite


I was wondering how I would move a sprite from the centre of the screen to being 10 pixels from the top edge of the screen. Thus making it look like its moving up.

This is my code so far

var LoginLayer = cc.Layer.extend({

init:function () {

    //////////////////////////////
    // 1. super init first
    this._super();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.
    // ask director the window size
    var size = cc.Director.getInstance().getWinSize();

    //Create Background Layer
    var background = cc.LayerColor.create( g_Colors.cedarWoodFinish, size.width, size.height);
    background.setAnchorPoint( cc.p(0.5,0.5) );

    //Create Logo Layer
    var logo = cc.Sprite.create(s_logo);
    logo.setAnchorPoint(cc.p(0.5, 1));
    logo.setPosition(cc.p(size.width / 2, size.height + ((logo.getContentSize().height * logo.getScaleY()) /2)));
    logo.setScale(0.5);

    //Add Layers To Scene
    this.addChild(background);
    this.addChild(logo);

    var logoMoveUpAnimation = cc.MoveTo.create(2, cc.p(size.width / 2, size.height - 10) );
    logo.runAction(logoMoveUpAnimation);
}
});

var LoginScene = cc.Scene.extend({
onEnter:function () {
    this._super();
    var layer = new LoginLayer();
    this.addChild(layer);
    layer.init();
}
});

Solution

  • what version of Cocos 2d-x you are using? for Cocos 2d-x rc0 2.1.3 you can move the Sprite with these lines of code.

    CCSize size = CCDirector::sharedDirector()->getWinSize();
    actualY = size.height - 10;
    CCFiniteTimeAction* actionMove = 
            CCMoveTo::create( 9.0,ccp(logo->getContentSize().width/2, actualY) );
             CCFiniteTimeAction* actionMoveDone = 
            CCCallFuncN::create( this, 
            callfuncN_selector(HelloWorld::LogoMoveFinished));
        logo->runAction( CCSequence::create(actionMove, 
            actionMoveDone, NULL) );
    

    Here logo is moved to position(logosize/2,screenheight-10pixels). when logo has been moved LogoMoveFinished function is called.