Search…

Hướng Dẫn Viết Game Zero Với Cocos2d-x - Phần 2: Hiện Thực LoadScene

30/09/20202 min read
Hướng dẫn cách để hiện thực một scene trong game, cũng như cách để chuyển scene với Cocos2d-x

Hướng dẫn hiện thực lại game ZERO 1 cách đơn giản. Giúp làm quen cách để hoàn thành 1 game, cũng như cách tổ chức project trong game.

Hướng dẫn cách để hiện thực 1 scene trong game, cũng như cách để chuyển scene. LoadScene chính là đối tượng được hướng đến trong bài viết này.

Hiện thực

LoadScene.h

Thêm vào biến m_loadingStep và override lại hàm update của scene như sau:

#ifndef __LOAD_SCENE_H__
#define __LOAD_SCENE_H__

#include "cocos2d.h"

class LoadScene : public cocos2d::Layer
{
public:
	// there's no 'id' in cpp, so we recommend returning the class instance pointer
	static cocos2d::Scene* createScene();

	// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
	virtual bool init();

	//
	void update(float dt);

	// implement the "static create()" method manually
	CREATE_FUNC(LoadScene);
private:
	int m_loadingStep;
};

#endif // __LOAD_SCENE_H__

LoadScene.cpp

Định nghĩa lại hàm update vừa khai báo ở trên như sau:

void LoadScene::update(float dt)
{
	switch (m_loadingStep)
	{
		// Load sprite
	case 0:
		SpriteFrameCache::getInstance()->addSpriteFramesWithFile("spr_sheet_zero.plist",
																 "spr_sheet_zero.png");
		break;
		// Load position
	case 1:
		break;
		// Load sounds
	case 2:
		break;
	case 3:
		Director::getInstance()->replaceScene(MainMenuScene::createScene());
		break;
	}
	m_loadingStep++;
}

Hàm này có chức năng load vào cái sprite, sounds, position,... Sau đó chuyển đến MainMenuScene. Để làm được điều này nhớ thêm #include "MainMenuScene.h" vào đầu file LoadScene.cpp.

Trong hàm init của scene khởi tạo m_loadingStep = 0 và gọi this->scheduleUpdate() như sau:

bool LoadScene::init()
{
	//////////////////////////////
	// 1. super init first
	if (!Layer::init())
	{
		return false;
	}

	Size visibleSize = Director::getInstance()->getVisibleSize();
	Vec2 origin = Director::getInstance()->getVisibleOrigin();

	m_loadingStep = 0;
	this->scheduleUpdate();

	return true;
}

Download LoadScene và Resources

LOADSCENE.ZIP

RESOURCES.ZIP

Bài chung series

IO Stream

IO Stream Co., Ltd

30 Trinh Dinh Thao, Hoa Thanh ward, Tan Phu district, Ho Chi Minh city, Vietnam
+84 28 22 00 11 12
developer@iostream.co

383/1 Quang Trung, ward 10, Go Vap district, Ho Chi Minh city
Business license number: 0311563559 issued by the Department of Planning and Investment of Ho Chi Minh City on February 23, 2012

©IO Stream, 2013 - 2024