【cocos2d-x 3.7 飞机大战】 决战南海I (一) 开始界面

        好久没写过博客了,现在把刚做的游戏发上来吧,以后要注意更新博客啦~!

游戏截图



游戏整体结构图



第一步 在 AppDelegate 中设定游戏界面大小以及缩放方式

cocos2d-x3.7新生成的项目中,AppDelegate有默认的界面大小以及缩放方式,这里,我对其作出一些更改,使其适应本项目

 Size frameSize = glview->getFrameSize();
	
	Size winSize=Size(450,750);
	
	float widthRate = frameSize.width/winSize.width;
	float heightRate = frameSize.height/winSize.height;
	
    if (widthRate > heightRate)
    {        
		glview->setDesignResolutionSize(winSize.width,
			winSize.height*heightRate/widthRate, ResolutionPolicy::NO_BORDER);
    }
 
    else
    { 
		glview->setDesignResolutionSize(winSize.width*widthRate/heightRate, winSize.height,
			ResolutionPolicy::NO_BORDER);
    }

游戏背景图片大小为 450*750,所以,这里以背景图片为标准,设置不同的缩放比例


第二步 更改HelloWorld类,使其成为启动界面

自带的HelloWorld类里面并没有太多内容,只要将其删除即可,然后,设计主界面

HelloWorld();

~HelloWorld();

// 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();
    
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);

在每一个场景中,一般都会出现上面的函数,以后在介绍其他类的时候,除非特殊情况,否则不再说明。


通过文章一开始的图片,我们可以看到,启动界面包含四个菜单项按钮,以及初始动画

	//预加载声音和图片
	void preLoadSoundAndPicture();

	//开始游戏
	void startGame(Ref* pSender);

	//高分记录
	void highScore(Ref* pSender);

	//游戏说明
	void aboutGame(Ref* pSender);

	//退出游戏
	void menuCloseCallback(cocos2d::Ref* pSender);

	//启动界面动画
	Animate* startMainAnimate();

	//卸载不必要的资源
	virtual void onExit();

	//响应键盘(主要针对Android)
	void onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event);


下面这个变量可以不必在头文件中声明,我们后面介绍另一种方式
EventListenerKeyboard* m_listener;



下面是cpp文件的实现

#include "HelloWorldScene.h"
#include "TollgateOne.h"
#include "ScoreScene.h"
#include "AboutGame.h"

USING_NS_CC;

HelloWorld::HelloWorld()
{

}

HelloWorld::~HelloWorld()
{
	Director::getInstance()->getEventDispatcher()->removeEventListener(m_listener);<span style="white-space:pre">	</span>//一定要记得在析构函数中移除
}

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();
    
    // 'layer' is an autorelease object
    auto 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;
    }

	//预加载声音 图片
	preLoadSoundAndPicture();

	//播放背景音乐
	CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("sound/game_start.mp3",true);
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

	//加载背景
	auto m_background = Sprite::createWithSpriteFrame(
		SpriteFrameCache::getInstance()->getSpriteFrameByName("backgroundStartGame.jpg"));
	m_background->setPosition(Vec2(origin.x + visibleSize.width / 2, visibleSize.height / 2));
	m_background->setAnchorPoint(Vec2(0.5, 0.5));
	this->addChild(m_background);

	//加载启动界面动画
	auto startSprite = Sprite::createWithSpriteFrameName("backgroundAnimate1.png");
	startSprite->setPosition(Vec2(origin.x + visibleSize.width / 2, visibleSize.height / 2));
	this->addChild(startSprite, 1);

	startSprite->runAction(this->startMainAnimate());


    /
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

	//开始游戏 按钮
	auto tempStart1 = Sprite::createWithSpriteFrameName("StartGame_nor.png");
	auto tempStart2 = Sprite::createWithSpriteFrameName("StartGame_touched.png");

	auto startItem = MenuItemSprite::create(
		tempStart1, tempStart2, CC_CALLBACK_1(HelloWorld::startGame, this)
		);

	//高分记录 按钮
	auto tempScore1 = Sprite::createWithSpriteFrameName("GameScore_nor.png");
	auto tempScore2 = Sprite::createWithSpriteFrameName("GameScore_touched.png");

	auto highScoreItem = MenuItemSprite::create(
		tempScore1, tempScore2, CC_CALLBACK_1(HelloWorld::highScore, this)
		);

	//游戏说明 按钮
	auto tempHelp1 = Sprite::createWithSpriteFrameName("GameHelp_nor.png");
	auto tempHelp2 = Sprite::createWithSpriteFrameName("GameHelp_touched.png");

	auto aboutGameItem = MenuItemSprite::create(
		tempHelp1, tempHelp2, CC_CALLBACK_1(HelloWorld::aboutGame, this)
		);

    //退出游戏 按钮
	auto tempOver1 = Sprite::createWithSpriteFrameName("GameOver_nor.png");
	auto tempOver2 = Sprite::createWithSpriteFrameName("GameOver_touched.png");

	auto closeItem = MenuItemSprite::create(
		tempOver1, tempOver2, CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)
		);

    // create menu, it's an autorelease object
	auto menu = Menu::create(startItem, highScoreItem, aboutGameItem,closeItem, NULL);
	menu->alignItemsVerticallyWithPadding(closeItem->getContentSize().height/2);
	menu->setPosition(Vec2(origin.x + visibleSize.width / 2, visibleSize.height / 2));
    this->addChild(menu, 1);

	//监听手机键盘
	m_listener = EventListenerKeyboard::create();
	m_listener->onKeyReleased = CC_CALLBACK_2(HelloWorld::onKeyReleased, this);
	Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(
		m_listener, this);

    return true;
}

//预加载声音 图片
void HelloWorld::preLoadSoundAndPicture()
{
	//加载声音
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sound/game_start.mp3");
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sound/game_over.wav");
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sound/BackgroundMusic.wav");

	CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect("sound/achievement.mp3");
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect("sound/bullet.wav");
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect("sound/button.mp3");
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect("sound/enemy1_down.wav");
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect("sound/enemy2_down.wav");
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect("sound/enemy3_down.wav");
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect("sound/get_bomb.mp3");
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect("sound/get_double_laser.mp3");
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect("sound/out_porp.mp3");
	CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect("sound/use_bomb.mp3");

	
	//加载图片
	SpriteFrameCache::getInstance()->addSpriteFramesWithFile("ui/background.plist");
	SpriteFrameCache::getInstance()->addSpriteFramesWithFile("ui/plane.plist");
}
//开始游戏
void HelloWorld::startGame(Ref* pSender)
{
	CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic();

	Director::getInstance()->replaceScene(TollgateOne::createScene());
}
//高分记录
void HelloWorld::highScore(Ref* pSender)
{
	Director::getInstance()->pushScene(
		TransitionProgressRadialCCW::create(1.0f, ScoreScene::createScene()));
}
//游戏说明
void HelloWorld::aboutGame(Ref* pSender)
{
	Director::getInstance()->pushScene(
		TransitionJumpZoom::create(1.0f, AboutGame::createScene()));
}

void HelloWorld::menuCloseCallback(Ref* pSender)
{
	Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
	exit(0);
#endif
}

//启动界面动画
Animate* HelloWorld::startMainAnimate()
{
	Vector<SpriteFrame*> vecStartAnimate;
	for (int i = 0; i < 5; i++)
	{
		auto tempString = __String::createWithFormat("backgroundAnimate%d.png", i + 1);
		auto tempAnimate = SpriteFrameCache::getInstance()->getSpriteFrameByName(tempString->getCString());

		vecStartAnimate.pushBack(tempAnimate);
	}

	auto animate = Animate::create(Animation::createWithSpriteFrames(
		vecStartAnimate, 0.5f, -1));

	return animate;
}

//卸载不必要的资源
void HelloWorld::onExit()
{
	Layer::onExit();
	Director::getInstance()->getTextureCache()->removeUnusedTextures();
}


//响应键盘(主要针对Android)
void HelloWorld::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event)
{
	if (keyCode == EventKeyboard::KeyCode::KEY_ESCAPE)
		Director::getInstance()->end();
}

之前一直用cocos2d-x2.2.6,现在换成3.7了,感觉变化挺大的。


游戏中用到的所有资源文件,会在最后上传。





在使用cocos2d-x框架开发飞机大战游戏时,实现敌人发射子弹的功能主要涉及以下几个步骤: 1. 创建子弹类:首先需要创建一个子弹类,这个类应该继承自`Cocos2d-x`的`Sprite`类或者其它适合的显示对象类。在这个类中定义子弹的基本属性,如速度、位置、大小等,并且可以添加子弹的一些动作,比如移动。 2. 发射子弹的逻辑:在敌人角色类中,添加发射子弹的逻辑。这通常会在一个周期性的函数中实现,例如每秒检查敌人是否需要发射子弹,如果需要,则创建子弹类的实例,并设置其初始位置为敌人当前位置。 3. 子弹的移动:子弹被创建后,需要使其按照一定的方向和速度移动。这可以通过使用`Action`来实现,例如使用`MoveTo`动作让子弹沿直线移动,或者使用`MoveBy`来相对当前位置移动。 4. 碰撞检测:为了实现子弹击中目标的功能,需要在游戏逻辑中添加碰撞检测。这可以通过`Cocos2d-x`提供的`PhysicsContact`监听或者简单的矩形碰撞检测来实现。当子弹与飞机等目标接触时,触发相应的逻辑,如减少生命值或者销毁目标。 5. 子弹的移除:当子弹离开屏幕或者击中目标后,应该将其从场景中移除,避免内存泄漏和不必要的渲染计算。 示例代码片段(伪代码): ```cpp class Bullet : public cocos2d::Sprite { public: Bullet(const cocos2d::Vec2& position, const cocos2d::Size& size) { // 初始化子弹位置、大小等属性 // 添加移动动作或使用回调函数定时更新子弹位置 } // 可以添加子弹移动更新的回调函数 void update(float dt) { // 根据时间间隔更新子弹位置 } }; class Enemy : public cocos2d::Sprite { public: void update(float dt) { // ... 其他更新逻辑 if (shouldFireBullet()) { // 创建子弹实例 Bullet* bullet = new Bullet(this->getPosition(), bulletSize); // 设置子弹的目标位置 bullet->setPosition(this->getPosition() + Vec2(0, -bulletSize.height)); // 将子弹添加到父节点或场景中 this->getParent()->addChild(bullet); // 可以添加一个移动动作或定时器来控制子弹移动 } } bool shouldFireBullet() { // 根据一定的逻辑判断是否发射子弹,例如定时发射 // 返回布尔值 } }; // 在适当的位置添加Enemy和Bullet类的实现和调用代码 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值