零基础学Cocos2d
// create a scene. it's an autorelease object Scene *scene = HelloWorld :: createScene (); // run director- runWithScene (scene); 那么接下来,我们看看这场戏到底内部是执行流程的
// create a scene. it's an autorelease object
Scene *scene = HelloWorld::createScene();
// run
director->runWithScene(scene);
那么接下来,我们看看这场戏到底内部是执行流程的啊。
OK,首先看看HelloWorldScene.h 到底有什么东西。
静态创建函数
static cocos2d::Scene* createScene();
初始化
virtualbool init();
菜单的一个回调函数
void menuCloseCallback(cocos2d::Ref* pSender);
这个。。。。看宏定义上面的注释说是创建一个特定的类
CREATE_FUNC(HelloWorld);
/** * define a create function for a specific type, such as Layer * @param \__TYPE__ class type to add create(), such as Layer */ #define CREATE_FUNC(__TYPE__) \ static __TYPE__* create() \ { \ __TYPE__ *pRet = new __TYPE__(); \ if (pRet && pRet->init()) \ { \ pRet->autorelease(); \ return pRet; \ } \ else \ { \ delete pRet; \ pRet = NULL; \ return NULL; \ } \ }
看完后 ,哦,,,,
CREATE_FUNC(HelloWorld);
就是相当于
在 HelloWorldScene.h 的定义
static HelloWorld* create();
在 HelloWorldScene.m 的实现
HelloWorld* HelloWorld::create() { //创建一个 HelloWorld 对象 HelloWorld* helloWorld = new HellWorld(); //判断 HelloWorld 对象是否创建以及初始化成功 if (helloWorld && helloWorld->init()) { //创建成功,初始化成功后,让其自动释放内存 helloWorld->autorelease(); //返回 HelloWorld 实例 return helloWorld; } else { //如果创建失败,将安全删除 HelloWorld 对象 delete helloWorld; helloWorld = NULL; return NULL; } }
好了,有宏的话,让我们剩下了不少代码的工作量啊。
接下来我们看看其他的吧
HelloWorldScene.cpp 的里面的函数的执行顺序是
先
Scene* HelloWorld::createScene();
再
bool HelloWorld::init();
Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auro layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; }
可以写成
Scene* HelloWorld::createScene() { // 'scene' is an autorelease object Scene* scene = Scene::create(); // 'layer' is an autorelease object Layer* layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; }
我们创建初始化一个场景后,然后又初始化一个层,将层放入场景里。
// on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Point::ZERO); this->addChild(menu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label auto label = LabelTTF::create("Hello World", "Arial", 24); // position the label on the center of the screen label->setPosition(Point(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1); // add "HelloWorld" splash screen" auto sprite = Sprite::create("HelloWorld.png"); // position the sprite on the center of the screen sprite->setPosition(Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); return true; }
虽然这段很长,不过包含了很多要学习的知识。
从表面上看,这段代码都在讲初始化的那些事。
细心观察,这个和Objective-C 的 init 方法多类似啊,只是不是返回对象。
我们精简一下这段代码的框架
bool HelloWorld::init() { if ( !Layer::init() ) { return false; } //初始化的内容 return true; }
接下来看看里面进行的初始化的内容吧
向导演问了相关舞台的数据
Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin();
然后搞一个按钮出来,这个按钮可以触发指定的事件
// 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Point::ZERO); this->addChild(menu, 1);
// 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object MenuItemImage* closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(Point(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2)); // create menu, it's an autorelease object Menu* menu = Menu::create(closeItem, NULL); menu->setPosition(Point::ZERO); this->addChild(menu, 1);
MenuItemImage 类 创建一个对象,放入两张图片,和一个回调函数。
第一张图片是正常状态的,第二张是选择状态时的,回调函数,this 应该是目标和iOS 创建按钮很相似,而区别是没有触发事件的手势设置。
接下来就是设置 MenuItemImage 类 实例的位置
通过 MenuItemImage 类 实例 创建一个 Menu 类的实例。
设置坐标
最后,将这个Menu类的实例加入当前 Layer中
接下来就是创建一个Label 类了。
根据官方发布文档所描述。3.0将采用一个Label 类 来创建不同类型的Label,而且优化了很多性能,这些也是后话了。
// 3. add your codes below... // add a label shows "Hello World" // create and initialize a label auto label = LabelTTF::create("Hello World", "Arial", 24); // position the label on the center of the screen label->setPosition(Point(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1);
创建一个LabelTTF类的实例,参数1是内容,参数2是字体,参数3是字体大小
然后就是设置 这个实例的位置
然后加入层
// add "HelloWorld" splash screen" auto sprite = Sprite::create("HelloWorld.png"); // position the sprite on the center of the screen sprite->setPosition(Point(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0);
首先用精灵创建一个实例,参数是一张图片。
然后设置精灵的位置。
最后把精灵加入层里,
最后我们看看回调函数吧,当点击按钮时,就会触发这个回调函数,因为已经关联上了。
void HelloWorld::menuCloseCallback(Ref* pSender) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert"); return; #endif Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif }
这里实现的功能很简单,就是退出应用程序而已。
好了,就这样就结束了。接下来就是详情了。
表面上看,Cocos2d-X 真的不难~~~
呵呵

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP는 웹 개발의 모든 작업을 처리할 수 있는 널리 사용되는 오픈 소스 서버 측 스크립팅 언어입니다. PHP는 웹 개발에 널리 사용되며, 특히 동적 데이터 처리에 뛰어난 성능을 발휘하여 많은 개발자들에게 사랑받고 사용되고 있습니다. 이 기사에서는 초보자가 시작부터 능숙해질 수 있도록 PHP의 기본 사항을 단계별로 설명합니다. 1. 기본 구문 PHP는 코드가 HTML, CSS 및 JavaScript와 유사한 해석 언어입니다. 모든 PHP 문은 세미콜론으로 끝납니다.

IT업계에 취업하고 싶지만 프로그래밍을 배우고 싶다면 어떤 기술을 선택해야 할까요? 당연히 리눅스 운영과 유지보수겠죠? Linux는 광범위한 응용 프로그램과 좋은 고용 전망을 제공하여 시장에서 매우 인기 있는 기술이며 많은 사람들이 선호합니다. 그렇다면 질문은, 기본 지식 없이도 리눅스 운영과 유지 관리를 배울 수 있느냐는 것입니다. 서버 시장에서 리눅스 시스템은 안정성, 보안성, 무료 오픈 소스, 효율성, 편의성 등의 장점으로 인해 최대 80%의 시장 점유율을 차지하고 있습니다. . 이것으로부터 Linux 애플리케이션이 매우 널리 사용된다는 것을 알 수 있습니다. 지금이든 미래이든 Linux를 배우는 것은 매우 좋은 선택입니다. 처음부터 배울 수 있는지에 대해서는 당연히 내 대답은 다음과 같습니다. 올드보이 교육 리눅스 대면 수업은 기초 지식이 전혀 없는 사람들을 위해 특별히 고안되었습니다.

Go 언어는 Google이 개발한 정적으로 유형이 지정되고 컴파일되는 언어로, 간결하고 효율적인 기능으로 인해 개발자들의 광범위한 관심과 사랑을 받았습니다. Go 언어를 학습하는 과정에서 변수에 대한 기본 지식을 익히는 것은 중요한 단계입니다. 이 글에서는 Go 언어의 변수 정의, 할당, 유형 추론 등의 기본 지식을 구체적인 코드 예제를 통해 설명하여 독자가 이러한 지식 포인트를 더 잘 이해하고 숙달할 수 있도록 돕습니다. Go 언어에서는 var 키워드를 사용하여 var 변수 이름 변수 유형의 형식인 변수를 정의할 수 있습니다.

PHP 기본 소개: 에코 함수를 사용하여 텍스트 내용을 출력하는 방법 PHP 프로그래밍에서는 일부 텍스트 내용을 웹 페이지에 출력해야 하는 경우가 많습니다. 이 기사에서는 echo 함수를 사용하여 텍스트 콘텐츠를 출력하는 방법을 소개하고 일부 샘플 코드를 제공합니다. 시작하기 전에 먼저 PHP를 설치하고 실행 환경을 구성했는지 확인하세요. 아직 PHP가 설치되지 않은 경우, PHP 공식 홈페이지(https://www.php.net)에서 최신 안정 버전을 다운로드 받으실 수 있습니다.

할 수 없습니다. CREATE 문의 기능은 테이블 구조를 생성하는 것이지만 새 레코드를 추가할 수는 없습니다. INSERT 문을 사용하여 새 레코드를 추가할 수 있습니다. CREATE 문을 사용하여 데이터베이스에 새 테이블을 만들고 데이터 열의 속성과 제약 조건을 지정할 수 있습니다. 그러나 새로 만든 테이블은 빈 테이블이므로 새 레코드를 추가하려면 INSERT 문을 사용해야 합니다. INSERT 문은 데이터베이스의 기존 테이블에 하나 이상의 튜플 데이터 행을 삽입하는 데 사용됩니다.

C 언어 함수 백과사전: 기본부터 고급까지, 함수 사용 방법에 대한 자세한 설명, 구체적인 코드 예제가 필요합니다. 소개: C 언어는 널리 사용되는 프로그래밍 언어이며 강력한 기능과 유연성으로 인해 많은 개발자가 첫 번째로 선택합니다. C 언어에서 함수는 코드 조각을 독립적인 모듈로 결합하여 코드의 재사용성과 유지 관리성을 향상시키는 중요한 개념입니다. 이 글에서는 C 언어 함수의 사용법을 기초부터 소개하고 점차적으로 발전시켜 독자들이 함수 작성 기술을 익히는 데 도움을 줄 것입니다. 1. C에서 함수 정의 및 호출

PHP 학습 노트: 객체 지향 프로그래밍의 기본, 특정 코드 예제가 필요합니다. 소개: 객체 지향 프로그래밍(OOP)은 문제를 여러 객체로 분해하고 객체 간의 상호 작용을 정의하여 복잡한 문제를 해결하는 프로그래밍 사고 방식입니다. 프로그래밍 문제. 강력한 프로그래밍 언어인 PHP는 객체 지향 프로그래밍도 지원합니다. 이 기사에서는 PHP의 객체 지향 프로그래밍의 기본 개념과 일반적인 구문을 소개하고 구체적인 코드 예제를 제공합니다. 친절한

PHP는 동적 웹사이트, 웹 애플리케이션 및 기타 인터넷 서비스를 개발하는 데 널리 사용되는 서버측 스크립팅 언어입니다. PHP 애플리케이션을 개발하는 과정에서 함수를 사용하면 코드를 단순화하고 코드 재사용성을 향상시키며 개발 비용을 줄이는 데 도움이 될 수 있습니다. 이 글에서는 PHP 함수의 기본 사용법과 고급 사용법을 소개합니다. 1. PHP 함수의 기본 사용법 1. 함수 정의 PHP에서는 function 키워드를 사용하여 함수를 정의합니다. 예: functiongreet($name){
