【cocos2dx 3.3】口袋空战2 子弹层

分析:

  • 子弹有自己的动作,故定义为Sprite类
  • 子弹需要做碰撞检测,故要设置物理属性
  • 子弹从飞机的旁边射出,故初始化要传入飞机的Y轴坐标
  • 子弹一旦发射,就一直向屏幕右端移动,用Moveto解决

子弹素材:




代码:


Bullet.h

#include "cocos2d.h"

USING_NS_CC;

class Bullet : public Sprite
{

public:

	//根据Y坐标初始化子弹位置
	static Bullet* create(float positionY);
	virtual bool init(float positionY);

	//获取屏幕大小
	Size visibleSize;

	//定义子弹精灵
	Sprite *bullet;

	//移除子弹
	void rm();

};


Bullet.cpp

#include "Bullet.h"

USING_NS_CC;

Bullet* Bullet::create(float positionY)
{
	Bullet *b = new Bullet();
	b->init(positionY);
	b->autorelease();
	return b;
}

bool Bullet::init(float positionY)
{
	Sprite::init();

	visibleSize = Director::getInstance()->getVisibleSize();

	bullet = Sprite::create("bullet.png");
	bullet->setPhysicsBody(PhysicsBody::createBox(bullet->getContentSize()));
	bullet->getPhysicsBody()->setGravityEnable(false);
	bullet->getPhysicsBody()->setContactTestBitmask(1);
	bullet->getPhysicsBody()->setTag(2);
	addChild(bullet);

	bullet->runAction(Sequence::create(MoveTo::create(0.5f,Point(visibleSize.width,positionY)),CallFuncN::create(CC_CALLBACK_0(Bullet::rm,this)),NULL));

	return true;
}


void Bullet::rm()
{
	bullet->removeFromParent();
}


你可能感兴趣的:(【cocos2dx 3.3】口袋空战2 子弹层)