Cocos2d x by example beginners guide

246 349 0
Cocos2d x by example beginners guide

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

fdsaf fsad fadd fdsad fsdaf sdafs af sfda vCocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1) Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1) Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)Cocos2dxbyExampleBeginnersGuideSecondEditionSampleChapter (1)

www.allitebooks.com Cocos2d-x by Example Beginner's Guide Make fun games for any platform using C++, combined with one of the most popular open source frameworks in the world Roger Engelbert BIRMINGHAM - MUMBAI www.allitebooks.com Cocos2d-x by Example Beginner's Guide Copyright © 2013 Packt Publishing All rights reserved No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews Every effort has been made in the preparation of this book to ensure the accuracy of the information presented However, the information contained in this book is sold without warranty, either express or implied Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals However, Packt Publishing cannot guarantee the accuracy of this information First published: April 2013 Production Reference: 1190413 Published by Packt Publishing Ltd Livery Place 35 Livery Street Birmingham B3 2PB, UK ISBN 978-1-78216-734-1 www.packtpub.com Cover Image by Roger Engelbert (rengelbert@gmail.com) www.allitebooks.com Credits Author Project Coordinator Roger Engelbert Abhishek Kori Reviewers Proofreader Fabio Cunha Dirk Manuel Stelios Pallis Marcio Valenzuela P Indexers Rekha Nair Monica Ajmera Mehta Acquisition Editor Martin Bell Graphics Lead Technical Editor Valentina D'silva Joel Noronha Production Coordinator Prachali Bhiwandkar Technical Editors Veronica Fernandes Ishita Malhi Saijul Shah Cover Work Prachali Bhiwandkar www.allitebooks.com About the Author Roger Engelbert is a game developer with over ten years of experience in developing online games He grew up surrounded by video games and thinks of classic, 8-bit arcade titles as a form of art He is the author behind the blog Done With Computers, which is chock-full of tutorials on game development and design Roger sincerely hopes to soon live in a world where people of all ages will be given the knowledge and opportunity to experience the joy of building their own games I would like to thank the people from Packt Publishing who helped me through the process of writing this book And above all, my family, who lovingly accepted my, "Sorry, I can't that, I'm writing a book" as an excuse to avoid every task and chore imaginable (I wonder how long I can keep giving that excuse now that the book has been published ) www.allitebooks.com About the Reviewers Fabio Cunha began web development about three years ago and worked as a mobile developer for two years He currently works as a frontend developer in an e-learning company He has his own blog (http://www.fabiosistemas.com.br/blog/) that describes all of the work that he does, and has published games on mobile platforms such as Android, iOS, and Blackberry I would like to thank my mother, brother, and sister for always supporting me, my dad for teaching me to be a calmer person, and my girlfriend for always staying by my side Stelios Pallis is 25 years old and lives in Cyprus He studied Computer Science at the University of Cyprus (UCY), and at the moment he is a postgraduate student there In 2011, he started developing games, and as a fanatic gamer he loved developing games In 2012, he founded a startup company called Gamethru, a company for developing mobiles games Gamethru has already published four mobile games; three are available in Google Play Store and one in App Store www.allitebooks.com Marcio Valenzuela P is a biochemist who has studied programming as a hobby for over 12 years He is perseverant, autodidactic, and is always looking into the latest technologies Marcio started by picking up ASP back in the early 90's as Chief Web Developer for a consulting firm that developed web applications for private companies He also delved into PHP applications with a MySQL database backend Then, in 2008, he started on his path down iOS and has had experience in developing applications and games for the platform His experience is mostly in business applications where there exists a cloud-based web service to interact with, and more recently, in games created in Cocos2d Marcio is the co-founder of Activasolutions.com and currently runs a small iOS project called Santiapps.com, which programs for companies wishing to enter the iOS platform Marcio is a forum moderator at RayWenderlich.com I would like to acknowledge the time I have taken from raising my son to dedicate to this book I just hope that someday Santiago follows in the programming tradition as it fosters critical skills such as problem-solving and innovation, which is something we share www.allitebooks.com www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy Get in touch with us at service@packtpub.com for more details At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks TM http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library Here, you can access, read and search across Packt's entire library of books Why Subscribe? ‹‹ Fully searchable across every book published by Packt ‹‹ Copy and paste, print and bookmark content ‹‹ On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books Simply use your login credentials for immediate access www.allitebooks.com www.allitebooks.com Table of Contents Preface 1 Chapter 1: Installation Download and installation Time for action – downloading and installing Cocos2d-x Hello-x World-x Time for action – creating an application The folder structure The iOS linkage classes The AppDelegate class The HelloWorldScene class Who begets whom 9 11 12 12 12 13 Further information Time for action – running the test samples The other tools Summary Chapter 2: You plus C++ plus Cocos2d-x Cocos2d-x – an introduction The containers The director and caches Then there is all the other stuff But you don't know C++? The interface Time for action – creating the interface The implementation Time for action – creating the implementation Instantiation and memory management Option – use static methods Option – C++, Cocos2d-x style www.allitebooks.com 13 14 14 15 17 17 18 19 19 19 20 20 22 22 23 24 25 Appendix A These perpendiculars are often called right and left, or clockwise and counterclockwise perpendiculars, and they are themselves vectors, known as normals Now if we calculate the dot product between the rocket's vector and each of the perpendiculars on line AB, you can see that we can determine the direction in which the rocket should rotate If the dot product of the rocket and the vector's right perpendicular is a positive value, it means the rocket is moving towards the right (clockwise) If not, it means the rocket is moving towards the left (counterclockwise) Calculate dot product of rocket and normals A dot > dot < B The dot product is very easy to calculate We don't even need to bother with the formula, though it's a simple one, because we can use the ccDot(vector1, vector2) method So we have the vector for the rocket already How we get the vector for the normals? First we get the vector for the AB line We use another method for this ccpSub(point1, point2); this will subtract points A and B and return a vector representing that line Next, we can get the left and right perpendiculars of that line vector with the ccpPerp(vector) and ccpRPerp(vector) methods respectively But we only need to check one of these Then we get the dot product by using ccpDot(rocketVector, lineNormal) If this is the correct normal, meaning the value for the dot product is a positive one, we can rotate the rocket to point to this normal's direction; so the rocket will be at a 90 degree angle with the line at all times as it rotates This is easy, because we can convert the normal vector to an angle by using the ccpToAngle(vector) method All we need to is apply that angle to the rocket But how fast should the rocket rotate? We'll see how to calculate that next [ 217 ] Vector Calculations with Cocos2d-x Moving from pixel-based speed to angular-based speed When rotating the rocket, we still want to show it moving at the same speed as it was when moving on a straight line, or as close to it as possible How we that? A B Remember that the vector is being used to update the rocket's position in every iteration In the example I gave you, the (5,0) vector is currently adding pixels to the x position of the rocket in every iteration Now let's consider an angular speed If the angular speed were 15 degrees, and we kept rotating the rocket's position by that angle, it would mean the rocket would complete a full circle in 24 iterations, because 360 degrees of a full circle divided by 15 degrees equals 24 But we don't have the correct angle yet, we only have the amount in pixels the rocket moves in every iteration But math can tell us a lot here Math says that the length of a circle is twice the value of Pi, multiplied by the radius of the circle, usually written as 2πr We know the radius of the circle that we want the rocket to describe: it is the length of the line we drew A RADIUS B [ 218 ] Appendix A With that formula we can get the length in pixels of that circle, also known as its circumference Let's say the line has a length of 100 pixels; this would mean the circle about to be described by the rocket has a length (or circumference) of 628.3 pixels (2 * π * 100) With the speed described in the vector (5,0), we can determine how long it would take the rocket to complete that pixel length We don't need this to be absolutely precise (the last iteration will most likely move beyond that total length) but it's good enough for our purposes A A Take circumference of circle Divide by rocket’s vector Find time to complete circle B (5,0) (5,0) (5,0) (5,0) (5,0) (5,0) (5,0) When we have the total number of iterations to complete the length, we can convert that to an angle So if the iteration value is 125, the angle would be 360 degrees divided by 125, that is 2.88 This is the angle required to describe a circle in 125 iterations Now the rocket can change from a pixel-based movement to an angular-based movement without much visual change [ 219 ] B Pop Quiz Answers Chapter 4, Fun with Sprites – Sky Defense Pop quiz – sprites and actions Q1 Q2 Q3 Q4 Chapter 8, Getting Physical – Box2D Pop quiz – Box2D Q1 Q2 Q3 Q4 Index Symbols _acceleration 189 _boom 86 _hasFloated property 109 -> notation 23 _pickup 86 bash_profile file 195 plist file creating 183 data, retrieving 184, 186 level data, loading 183 _rocket sprite 98 _star 86 warp 86 A accelerometer data, reading 189, 190 using 189 actual game scene main loop, adding 44-47 multi-touches, handling 41, 43 scores, updating 47, 49 addBlocks method 116 air hockey game about 29 game configurations 30 project, creating 30 rules, laying down 30, 31 Android project code, compiling 196, 197 creating, with Cocos2d-x 195, 196 Android SDK 194 AppDelegateclass 12 ARC 23 Automatic Reference Counting See  ARC B b2Bodies method 169 b2Body about 190 changing 190, 191 b2Sprite class 156 Ball class 159 ball objects, Mini Pool creating 159, 160 batch drawing sprites about 55 CCSpriteBatchNode, adding 56, 57 bitmap fonts, Cocos2d-x about 58, 59 final screen sprites, adding 60-62 object pools, creating 63, 64 tables, creating 60-62 Block object 108 bodies meeting 154 boolean property 126 Box2D 152 Box2D hybrid project creating 209 Box2D project basic template, preparing 149-151 creating, with Cocos2d-x 149-151 C CCActions about 64 creating, in Cocos2d-x 64-66 ccDot(vector1, vector2) method 217 CCInteger wrapper 26 CCLayer 18 CCNode 19 CCNotificationCenter using 188, 189 CCObject benefits 26 ccpAdd(vector1, vector2) method 214 ccpDot(vector1, vector2) method 214 ccpForAngle(angle) method 214 ccp helper methods using 214 ccpLength(vector) method 214 CCLayer::init method 38 CCMoveToaction 76 ccpMult(vector1, value) method 214 CCNotificationCenter using 188 ccpPerp(vector) method 214 ccpRotateByAngle method 215 ccpRPerp(vector) method 214 ccpSub(point1, point2) method 217 ccpSub(vector1, vector2) method 214 ccpToAngle(vector) method 214, 217 CCScene 18 CCScenes, in Cocos2d-x transitions, creating 180,181 using 179, 180 CCSprite method 18, 169 CCString wrapper 26 CCTargetedTouchDelegate protocol 43 ccTouchesBegan method 69 ccTouchesMoved method 94 Cocos2d-x about 17, 18 C++ 19, 20 cache 19 CCAction 19 CCParticles 19 containers 18, 19 director 19 primitives, drawings 88 specialized CCNodes 19 sprite, animating 66 cocos2dx_box2d template option 148 collision filters, MiniPool creating 160 containers with containers 137-138 contact listener, MiniPool creating 162-165 controls adding 126 main loop, coding 128, 129 touches, handling 126, 127 createGameScreen method 107, 144 create method 24 createPools method 63 cue ball, Mini Pool creating 161, 162 D dot product using, of vectors 216, 217 E Eclipse about, 194 application, running 200-205 C++ code, compiling 202-206 C++ compiler, installing 197, 198 Cocos2d-x library, adding to 198 project, opening in 198, 199 using 197 edges, MiniPool creating 158 [ 224 ] Eskimo game about 175 settings 176, 177 external data loading, from plist file 182 G game CCNotificationCenter, using 188, 189 notifications, using 187 playing 78 game controls, MiniPool about 165 touch events, adding 165-169 game data completed levels, storing 186, 187 saving 186 game loop about 98 adding 98-101 game settings, MiniPool 156 game ticks about 68 game updating 73-75 pool objects, retrieving 75 start logic 71-73 stop logic 71-73 touch handling 69, 71 grid, creating 88 GLES-Render class 151 Glyph Designer 15 H HelloWorld class implementation about 22 creating 22, 23 Hello-x World-x AppDelegate class 12 folder structure 11 HelloWorldScene class 12 iOS linkage classes 12 hybrid game developing 210 hybrid project creating 206, 207 I initBlock method initPhysics method 151 installation, C++ compiler 197, 198 interface creating 20, 21 K killPlayer method 102 kills adding 102, 104 kResolutionExactFit parameter 84 L LineContainer object 166 M main loop, MiniPool about 169 adding 170, 171 MenuLayer::scene method 179 memory management about 23 C++ 25 Cocos2d-x style 25 static method, using 24 menu, adding to Victorian Rush Hour game about 140 CCMenu, creating 141-143 CCMenuItem, creating 141-143 methods, vectors ccpAdd(vector1, vector2) 214 ccpDot(vector1, vector2) 214 ccpForAngle(angle) 214 ccpLength(vector) 214 ccpMult(vector1, value) 214 ccpPerp(vector) 214 ccpRPerp(vector) 214 ccpSub(vector1, vector2) 214 ccpToAngle(vector) 214 m_fRotation property 93 MiniPool about 155 ball objects, creating 159, 160 [ 225 ] collision filters, creating 160, 161 contact listener, creating 162-164 cue ball, creating 161, 162 edges, creating 158 game controls 165 game settings 158 main loop 169 main loop, adding 170, 171 pool table, creating 157, 158 timer, adding 171, 172 N Native Development Kit 194 O onGravityChanged method 188 P parallax effect creating 138-140 Particle Designer 14 particles 84 particle systems creating, 85, 86 pixel based speed to angular based speed 218, 219 platform collision logic about 123 detector, adding 123-125 Player object 108 point rocket, rotating around 215, 216 vector, comparing with 213 primitives, Cocos2d-x drawing, 88-90 primitives, Cocos2d-x drawing 88-90 project opening, in Eclipse 198, 199 R rapid prototyping place holder sprites, creating 106, 107 resetGame method 103 resets adding 102, 104 rocket rotating, around point 215, 216 Rocket sprite touches, handling 94-98 updating 93 Rocket through game about 81 screen settings, 83, 84 settings 81 S schedule method 172 setDisplayFrame method 136 setPivot method 97 setupBlock method 112 showTutorial method 144 Sky Defense game about 51, 52 background music, adding 53 initializing 53, 54 screen support, adding for universal app 52, 53 setttings 52 start project 52 Soundeffects, adding 32 sprite animation, Cocos2d-x about 66 creating 66-68 sprite sheets batch drawing sprites, 55 using, in Cocos2d-x 55 Start Project option 83 Step() method 169 stopAllActions() method 71 supportedInterfaceOrientations method 31 T Terrain class planning 113, 114 terrain object about 108 Block object, coding 112, 113 building 114 player, coding 109-111 Terrain class, initialising 115, 116 [ 226 ] test samples running 14 timer, MiniPool adding 171, 172 touch events adding 167-169 tutorial, adding to Victorian Rush Hour game about, 143 steps 144-146 versions Victorian Rush Hour game about 105, 106 animations 133 sprites 132 menu, adding 140 settings 106 tutorial, adding 143 virtual keyword 21 U X unschedule(SEL_SCHEDULE selector) method 172 update method 93, 109, 144, 169 Xcode V Zwoptex 14 Z vectors about 213 comparing, with point 213 dot product, using 216, 217 methods 214 [ 227 ] Thank you for buying Cocos2d-x by Example Beginner's Guide About Packt Publishing Packt, pronounced 'packed', published its first book "Mastering phpMyAdmin for Effective MySQL Management" in April 2004 and subsequently continued to specialize in publishing highly focused books on specific technologies and solutions Our books and publications share the experiences of your fellow IT professionals in adapting and customizing today's systems, applications, and frameworks Our solution based books give you the knowledge and power to customize the software and technologies you're using to get the job done Packt books are more specific and less general than the IT books you have seen in the past Our unique business model allows us to bring you more focused information, giving you more of what you need to know, and less of what you don't Packt is a modern, yet unique publishing company, which focuses on producing quality, cutting-edge books for communities of developers, administrators, and newbies alike For more information, please visit our website: www.packtpub.com About Packt Open Source In 2010, Packt launched two new brands, Packt Open Source and Packt Enterprise, in order to continue its focus on specialization This book is part of the Packt Open Source brand, home to books published on software built around Open Source licences, and offering information to anybody from advanced developers to budding web designers The Open Source brand also runs Packt's Open Source Royalty Scheme, by which Packt gives a royalty to each Open Source project about whose software a book is sold Writing for Packt We welcome all inquiries from people who are interested in authoring Book proposals should be sent to author@packtpub.com If your book idea is still at an early stage and you would like to discuss it first before writing a formal book proposal, contact us; one of our commissioning editors will get in touch with you We're not just looking for published authors; if you have strong technical skills but no writing experience, our experienced editors can help you develop a writing career, or simply get some additional reward for your expertise Cocos2d for iPhone Game Development Cookbook ISBN: 978-1-84951-400-2 Paperback: 446 pages Over 90 recipes for iOS 2D game development using cocos2d Discover advanced Cocos2d, OpenGL ES, and iOS techniques spanning all areas of the game development process Learn how to create top-down isometric games, side-scrolling platformers, and games with realistic lighting Full of fun and engaging recipes with modular libraries that can be plugged into your project Cocos2d for iPhone 0.99 Beginner's Guide ISBN: 978-1-84951-316-6 Paperback: 368 pages Make mind-blowing 2D games for iPhone with this fast, flexible, and easy-to-use framework! A cool guide to learning cocos2d with iPhone to get you into the iPhone game industry quickly Learn all the aspects of cocos2d while building three different games Add a lot of trendy features such as particles and tilemaps to your games to captivate your players Full of illustrations, diagrams, and tips for building iPhone games, with clear step-by-step instructions and practical examples Please check www.PacktPub.com for information on our titles Creating Games with cocos2d for iPhone ISBN: 978-1-84951-900-7 Paperback: 388 pages Master cocos2d through building nine complete games for the iPhone Games are explained in detail, from the design decisions to the code itself Learn to build a wide variety of game types, from a memory tile game to an endless runner Use different design approaches to help you explore the cocos2d framework Corona SDK Mobile Game Development: Beginner's Guide ISBN: 978-1-84969-188-8 Paperback: 408 pages Create monetized games for iOS and Android with minimum cost and code Build once and deploy your games to both iOS and Android Create commercially successful games by applying several monetization techniques and tools Create three fun games and integrate them with social networks such as Twitter and Facebook Please check www.PacktPub.com for information on our titles .. .Cocos2d-x by Example Beginner's Guide Make fun games for any platform using C++, combined with one of the most popular... frameworks in the world Roger Engelbert BIRMINGHAM - MUMBAI www.allitebooks.com Cocos2d-x by Example Beginner's Guide Copyright © 2013 Packt Publishing All rights reserved No part of this book... Installation, guides you through the download and installation of the Cocos2d-x framework It also examines the ins and outs of a basic Cocos2d-x application Chapter 2, You plus C++ plus Cocos2d-x,

Ngày đăng: 26/03/2018, 14:31

Từ khóa liên quan

Mục lục

  • Cover

  • Copyright

  • Credits

  • About the Author

  • About the Reviewers

  • www.PacktPub.com

  • Table of Contents

  • Preface

  • Chapter 1: Installation

    • Download and installation

    • Time for action – downloading and installing Cocos2d-x

    • Hello-x World-x

    • Time for action – creating an application

      • The folder structure

        • The iOS linkage classes

        • The AppDelegate class

        • The HelloWorldScene class

        • Who begets whom

        • Further information

        • Time for action – running the test samples

        • The other tools

        • Summary

        • Chapter 2: You plus C++ plus Cocos2d-x

          • Cocos2d-x – an introduction

            • The containers

Tài liệu cùng người dùng

Tài liệu liên quan