Cocos2d-JS의 API/Wiki 문서를 일일이 찾아다니기 귀찮으므로 여기에 간단히 정리
본 문서는 주로 아래의 내용을 정리한 것임
먼저 Cocos2d JS 프로젝트를 생성하였을 때의 폴더구조를 살펴보자.
// create sprite var sprite = cc.Sprite.create ( "bottomleft.png" ) ; sprite.attr({ x: 0, y: 0, anchorX: 0, anchorY: 0 }); this.addChild ( sprite ) ;
// Move a sprite 50 pixels to the right, and 10 pixels to the top over 2 seconds. sprite.runAction(cc.MoveBy.create(2, cc.p(50, 10)));
var animation = cc.Animation.create ( ) ; for ( var i = 1 ; i < 15 ; i ++ ) { var frameName = "res/Images/grossini_dance_" + ( ( i < 10 ) ? ( "0" + i ) : i ) + ".png" ; animation. addSpriteFrameWithFile ( frameName ) ; } animation.setDelayPerUnit ( 2.8 / 14 ) ; animation.setRestoreOriginalFrame ( true ) ; var action = cc.Animate.create ( animation ) ; sprite. runAction ( cc.Sequence.create( action, action. reverse ( ) ) ) ;
만약 여러 개의 sprite로 구성된 sprite sheet를 불러오고 plist 파일을 애니메이션 파일로 사용한다면 특정 프레임의 이미지를 가져올 때 파일명 앞에 #을 붙여야 한다.
this.sprite = cc.Sprite.create("#runner0.png");
child노드의 onEnter(), onEnterTransitionDidFinish()를 호출한다.1) Layer나 Scene 등에 child 노드를 추가하면 반드시 호출해야 한다.
자세한 내용은 여기 참고
//1. sprite 프레임 이름으로 PhysicsSprite 생성 this.sprite = cc.PhysicsSprite.create("#runner0.png"); var contentSize = this.sprite.getContentSize(); // 2. runner의 physic body 초기화 this.body = new cp.Body(1, cp.momentForBox(1, contentSize.width, contentSize.height)); //3. set the position of the runner this.body.p = cc.p(g_runnerStartX, g_groundHight + contentSize.height / 2); //4. apply impulse to the body this.body.applyImpulse(cp.v(150, 0), cp.v(0, 0));//run speed //5. add the created body to space this.space.addBody(this.body); //6. create the shape for the body this.shape = new cp.BoxShape(this.body, contentSize.width - 14, contentSize.height); //7. add shape to space this.space.addShape(this.shape); //8. set body to the physic sprite this.sprite.setBody(this.body);
여기 참고.
var GameLayer = cc.Layer.extend({ init:function () { var self = this; // ...... this.curPosition = null; if( 'mouse' in sys.capabilities ) { //this.setMouseEnabled(true); this.mouseCaptured = false; canvas = document.getElementById('gameCanvas'); canvas.addEventListener('mousemove', function(evt) { var rect = document.getElementById('gameCanvas').getBoundingClientRect(); var curPos = new cc.Point(); curPos.x = evt.clientX - rect.left; curPos.y = evt.clientY - rect.top; self.curPosition = curPos self.updatePosition(curPos); }, false); } // ...... }, updatePosition:function (position) { this.currentPosition = position; // ...... } });
현재 레이어에서 this.runActoin을 실행하면 this가 cc.Node의 멤버변수 target으로 전달된다. 이 target 변수는 callFunc를 이용하여 함수를 실행할 때 첫 번째 인자로 전달된다.
기본 형식은 다음과 같다.
cc.CallFunc.create(selector, selectorTarget, data)
selector는 실행될 함수이다. 꼭 지정해주어야 한다. 뒤의 selectorTarget, data 인자는 지정해주지 않아도 된다. selectorTarget은 selector함수를 selectorTarget context로 실행하게 한다. 즉, selector.call 함수의 첫 번째 인자로 들어가게 된다. data는 세 번째 인자로 전달된다. (두 번째 인자는 위에서 언급한 target이다)