====== Cocos2d-JS 문법 ====== Cocos2d-JS의 API/Wiki 문서를 일일이 찾아다니기 귀찮으므로 여기에 간단히 정리 //본 문서는 주로 아래의 내용을 정리한 것임// * [[http://cocos2d-x.org/|공식홈페이지]] - Learn - Docs - Framework - Cocos2d-html5 - New features and API changes in version 3.0 * [[http://cocos2d-x.org/|공식홈페이지]] - Learn - Docs - Tutorials - Pakour Game with Javascript (Cocos2d-JS v3.0) ===== 폴더 구조 ===== 먼저 Cocos2d JS 프로젝트를 생성하였을 때의 폴더구조를 살펴보자. {{:programming:javascript:cocos2d-js:newnavigator.jpg|}} * **frameworks 폴더** : cocos2d 엔진이 담겨있는 폴더 * **res 폴더** : 게임에 필요한 리소스 포함 * **src 폴더** : 소스가 포함된 폴더. **app.js**는 게임의 첫 번째 장면을 나타내는 파일. **resource.js**는 리소스의 전역 변수들을 정의한 파일. * **index.html** : HTML5 기반 웹 어플리케이션의 시작페이지. Viewpoint, 풀스크린 설정 등의 메타 데이터 포함. * **project.json** : 프로젝트 설정 파일. 소스 파일 등을 여기에 추가해야 한다. [[http://www.cocos2d-x.org/docs/manual/framework/html5/v3/project-json/en|여기]] 참고. * **main.js** : 첫 번째 장면을 만들어주는 코드. 해상도 정책을 정의하고 리소스를 미리 로드. ===== 기본 사항 ===== * [[http://cocos2d-x.org/wiki/Director|Director]] * [[http://cocos2d-x.org/wiki/Layer|Layer]] * [[http://cocos2d-x.org/wiki/Scene|Scene]] * [[http://cocos2d-x.org/wiki/Sprite|Sprite]] * [[http://cocos2d-x.org/wiki/Coordinate_System|Coordinate System]] // create sprite var sprite = cc.Sprite.create ( "bottomleft.png" ) ; sprite.attr({ x: 0, y: 0, anchorX: 0, anchorY: 0 }); this.addChild ( sprite ) ; * [[http://cocos2d-x.org/wiki/Actions|Action]] : Position, Scale, Rotation, Visibility, Opacity, Color 등의 속성을 변경 // 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))); * [[http://cocos2d-x.org/wiki/Animations|Animation]] 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"); * [[http://cocos2d-x.org/wiki/Scheduler|Scheduler]] * [[http://www.cocos2d-x.org/docs/manual/framework/html5/v3/eventManager/en|EventManager]] * addchild 함수 child노드의 onEnter(), onEnterTransitionDidFinish()를 호출한다.((http://codeng.tistory.com/160)) Layer나 Scene 등에 child 노드를 추가하면 반드시 호출해야 한다. ===== Chipmunk ===== 자세한 내용은 [[http://www.cocos2d-x.org/wiki/Chipmunk|여기]] 참고 ==== 기본 예제 ==== //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); ===== 이벤트 ===== ==== Mouse Over ==== [[http://stackoverflow.com/questions/18080504/html5-mousemove-event-in-cocos2d-html5|여기]] 참고. 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; // ...... } }); ===== Action ===== ==== runAction ==== 현재 레이어에서 this.runActoin을 실행하면 this가 cc.Node의 멤버변수 target으로 전달된다. 이 target 변수는 callFunc를 이용하여 함수를 실행할 때 첫 번째 인자로 전달된다. ==== cc.callFunc ==== 기본 형식은 다음과 같다. cc.CallFunc.create(selector, selectorTarget, data) selector는 실행될 함수이다. 꼭 지정해주어야 한다. 뒤의 selectorTarget, data 인자는 지정해주지 않아도 된다. selectorTarget은 selector함수를 selectorTarget context로 실행하게 한다. 즉, selector.call 함수의 첫 번째 인자로 들어가게 된다. data는 세 번째 인자로 전달된다. (두 번째 인자는 위에서 언급한 target이다) ====== 참고 ====== * [[http://cocos2d-x.org/docs/README|공식 홈페이지 Docs 문서]]