cocos2dx 打武器玩法实现

cocos2dx 打武器玩法实现,第1张

概述实现一个从空中飞来各种武器:飞镖,菜刀,斧头、刀子,还有各种蔬菜水果作为障碍物,所有东西飞向屏幕中央,主角站在正中心去躲避武器,武器打到身上会受到伤害,蔬菜水果不会,代码实现如下: .h文件 #ifndef __SCATTER_H__#define __SCATTER_H__#include "cocos2d.h"#include "Box2D/Box2D.h"#include "Char 实现一个从空中飞来各种武器:飞镖,菜刀,斧头、刀子,还有各种蔬菜水果作为障碍物,所有东西飞向屏幕中央,主角站在正中心去躲避武器,武器打到身上会受到伤害,蔬菜水果不会,代码实现如下:

.h文件

#ifndef __SCATTER_H__#define __SCATTER_H__#include "cocos2d.h"#include "Box2D/Box2D.h"#include "Characters/Hero.h"#include "Characters/Hero2.h"#include "Characters/Hero3.h"#include "Characters/Hero4.h"#include "global.h"class GameScene;#include "Scene/GameScene.h"USING_NS_CC;  class SmritiShadow:public CCNode{public:	~SmritiShadow();	voID draw();	CREATE_FUNC(SmritiShadow)		bool init();	voID onDraw();	static voID reset();	voID setTarget(CCSprite* spr,CCTexture2D* tex);	static CCGLProgram * pg;	CCSprite* target;	CCTexture2D *texture2d;	Vertex *Vertices;	long pretime;	int arrcount;	gluint vertexBuffer;	gluint indexBuffer;};class BodyDef;class b2Body;namespace cocos2d {	class GB2ShapeCache {	public:		// Static interface		static GB2ShapeCache* sharedGB2ShapeCache(voID);	public:		bool init();					voID addShapesWithfile(const std::string &pList);		voID addFixturesToBody(b2Body *body,const std::string &shape);		cocos2d::CCPoint anchorPointForShape(const std::string &shape);		voID reset();		float getPtmRatio() { return ptmRatio; }		~GB2ShapeCache() {}	private:		std::map<std::string,BodyDef *> shapeObjects;		GB2ShapeCache(voID) {}		float ptmRatio;	};}class ContactListener : public b2ContactListener{public:	voID BeginContact(b2Contact* contact);	voID EndContact(b2Contact* contact);};class Scatter:public CCNode{public:	~Scatter();	static Scatter* gthis;	virtual voID draw();	voID onDraw();	CREATE_FUNC(Scatter)	bool init();	voID addNewSpriteWithCoords(CCPoint p);	voID addBullet(int dr);	voID update(float dt);	voID porr();	voID setdifficulty(float df);	voID touchhandle(CCPoint curpt);	voID attackhandle(b2Body* b);	voID reset();	voID delayremove(CCNode* node,voID* param);	voID setHitct(int ct);	voID setoverListener(CCObject* pSelectorTarget,SEL_CallFunc win,SEL_CallFunc fail);	CCObject* m_pSelector;	ContactListener* contactListener;	CCTexture2D *texture2d;	SEL_CallFunc m_wsc,m_fsc;	b2World *m_world;	std::vector<b2Body*> m_bodIEs;	voID setoff(float x);	Hero *hero;	float m_level,m_levelf;	long pretime,pretimef;	float attackdelay;	CCPoint attackpoint;	int m_curhitcount,m_hitct;	int isover,ispause,status;	float speed;	float  xoff;	float mindis;	voID actionOver(CCObject* node,voID* param);	std::map<CCSprite*,CCNode*> m_tars;	long m_killemenynum; //杀敌数目	long m_levelscore;//关卡分数	long m_herohurttimes;//主角受伤次数	long m_goldNum;	long m_combomnum;	long m_maxcombom;	long m_perfectnum;	long m_greatenum;	GameScene *m_s;	int hurts[7];	voID UpdateLevelData();//更新关卡分数和敌人数目	voID PlayEffects();};#endif

.cpp文件
#include "Scatter.h"#include "Scene/GameLayer.h"#include "Common/GameSound.h"#include "Common/defines.h"#include "Common/Game.h"#include "Common/EnterStageDataExchange.h"#include "Modules/Archive.h"#include "SuckBlood.h"#include "GameLogic/GameLogic.h"class FixtureDef {public:	FixtureDef()		: next(NulL) {}	~FixtureDef() {		delete next;		delete fixture.shape;	}	FixtureDef *next;	b2FixtureDef fixture;	int callbackData;};class BodyDef {public:	BodyDef()		: fixtures(NulL) {}	~BodyDef() {		if (fixtures)			delete fixtures;	}	FixtureDef *fixtures;	CCPoint anchorPoint;};static GB2ShapeCache *_sharedGB2ShapeCache = NulL;GB2ShapeCache* GB2ShapeCache::sharedGB2ShapeCache(voID) {	if (!_sharedGB2ShapeCache) {		_sharedGB2ShapeCache = new GB2ShapeCache();		_sharedGB2ShapeCache->init();	}	return _sharedGB2ShapeCache;}bool GB2ShapeCache::init() {	return true;}voID GB2ShapeCache::reset() {	std::map<std::string,BodyDef *>::iterator iter;	for (iter = shapeObjects.begin() ; iter != shapeObjects.end() ; ++iter) {		delete iter->second;	}	shapeObjects.clear();}voID GB2ShapeCache::addFixturesToBody(b2Body *body,const std::string &shape) {	std::map<std::string,BodyDef *>::iterator pos = shapeObjects.find(shape);	assert(pos != shapeObjects.end());	BodyDef *so = (*pos).second;	FixtureDef *fix = so->fixtures;	while (fix) {		body->CreateFixture(&fix->fixture);		fix = fix->next;	}}cocos2d::CCPoint GB2ShapeCache::anchorPointForShape(const std::string &shape) {	std::map<std::string,BodyDef *>::iterator pos = shapeObjects.find(shape);	assert(pos != shapeObjects.end());	BodyDef *bd = (*pos).second;	return bd->anchorPoint;}voID GB2ShapeCache::addShapesWithfile(const std::string &pList) {	//const char *fullname = CCfileUtils::sharedfileUtils()->fullPathForfilename(pList.c_str()).c_str();	CCDictionary *dict = CCDictionary::createWithContentsOffile(pList.c_str());	// not triggered - cocos2dx delivers empty dict if non was found	CCAssert(dict != NulL,"Shape-file not found");	CCAssert(dict->count() != 0,"pList file empty or not existing");	CCDictionary *MetadataDict = (CCDictionary *)dict->objectForKey("Metadata");	int format = static_cast<CCString *>(MetadataDict->objectForKey("format"))->intValue();	ptmRatio = static_cast<CCString *>(MetadataDict->objectForKey("ptm_ratio"))->floatValue();	cclOG("ptmRatio = %f",ptmRatio);	CCAssert(format == 1,"Format not supported");	CCDictionary *bodyDict = (CCDictionary *)dict->objectForKey("bodIEs");	b2Vec2 vertices[b2_maxpolygonVertices];	CCDictElement *dictElem;	std::string bodyname;	CCDictionary *bodyData;	//iterate body List	CCDICT_FOREACH(bodyDict,dictElem )	{		bodyData = (CCDictionary*)dictElem->getobject();		bodyname = dictElem->getStrKey();		BodyDef *bodyDef = new BodyDef();		bodyDef->anchorPoint = CCPointFromString(static_cast<CCString *>(bodyData->objectForKey("anchorpoint"))->getCString());		CCArray *fixtureList = (CCArray*)(bodyData->objectForKey("fixtures"));		FixtureDef **nextFixtureDef = &(bodyDef->fixtures);		//iterate fixture List		CCObject *arrayElem;		CCARRAY_FOREACH(fixtureList,arrayElem)		{			b2FixtureDef basicdata;			CCDictionary* fixtureData = (CCDictionary*)arrayElem;			basicdata.filter.categoryBits = static_cast<CCString *>(fixtureData->objectForKey("filter_categoryBits"))->intValue();			basicdata.filter.maskBits = static_cast<CCString *>(fixtureData->objectForKey("filter_maskBits"))->intValue();			basicdata.filter.groupIndex = static_cast<CCString *>(fixtureData->objectForKey("filter_groupIndex"))->intValue();			basicdata.friction = static_cast<CCString *>(fixtureData->objectForKey("friction"))->floatValue();			basicdata.density = static_cast<CCString *>(fixtureData->objectForKey("density"))->floatValue();			basicdata.restitution = static_cast<CCString *>(fixtureData->objectForKey("restitution"))->floatValue();			basicdata.isSensor = (bool)static_cast<CCString *>(fixtureData->objectForKey("isSensor"))->intValue();			CCString *cb = static_cast<CCString *>(fixtureData->objectForKey("userdataCbValue"));			int callbackData = 0;			if (cb)				callbackData = cb->intValue();			std::string fixtureType = static_cast<CCString *>(fixtureData->objectForKey("fixture_type"))->m_sstring;			if (fixtureType == "polyGON") {				CCArray *polygonsArray = (CCArray *)(fixtureData->objectForKey("polygons"));				CCObject *dicArrayElem;				CCARRAY_FOREACH(polygonsArray,dicArrayElem)				{					FixtureDef *fix = new FixtureDef();					fix->fixture = basicdata; // copy basic data					fix->callbackData = callbackData;					b2polygonShape *polyshape = new b2polygonShape();					int vindex = 0;					CCArray *polygonArray = (CCArray*)dicArrayElem;					assert(polygonArray->count() <= b2_maxpolygonVertices);					CCObject *piter;					CCARRAY_FOREACH(polygonArray,piter)					{						CCString *verStr = (CCString*)piter;						CCPoint offset = CCPointFromString(verStr->getCString());						vertices[vindex].x = (offset.x / ptmRatio) ;						vertices[vindex].y = (offset.y / ptmRatio) ;						vindex++;					}					polyshape->Set(vertices,vindex);					fix->fixture.shape = polyshape;					// create a List					*nextFixtureDef = fix;					nextFixtureDef = &(fix->next);				}			}			else if (fixtureType == "CIRCLE") {				FixtureDef *fix = new FixtureDef();				fix->fixture = basicdata; // copy basic data				fix->callbackData = callbackData;				CCDictionary *circleData = (CCDictionary *)fixtureData->objectForKey("circle");				b2CircleShape *circleShape = new b2CircleShape();				circleShape->m_radius = static_cast<CCString *>(circleData->objectForKey("radius"))->floatValue() / ptmRatio;				CCPoint p = CCPointFromString(static_cast<CCString *>(circleData->objectForKey("position"))->getCString());				circleShape->m_p = b2Vec2(p.x / ptmRatio,p.y / ptmRatio);				fix->fixture.shape = circleShape;				// create a List				*nextFixtureDef = fix;				nextFixtureDef = &(fix->next);			}			else {				CCAssert(0,"UnkNown fixtureType");			}		}		// add the body element to the hash		shapeObjects[bodyname] = bodyDef;	}}const char* vertshader="\					   attribute vec4 a_position;\					   attribute vec2 a_texCoord;\					   attribute vec4 a_color;\					   varying vec4 v_fragmentcolor;\					   varying vec2 v_texCoord;\					   voID main()\					   {\					   gl_position = CC_MVPMatrix * a_position;\					   v_fragmentcolor = a_color;\					   v_texCoord = a_texCoord;\					   }";const char* fragshader="\					   varying vec4 v_fragmentcolor;\					   varying vec2 v_texCoord;\					   uniform sampler2D CC_Texture0;\					   voID main()\					   { \					   vec4 color=texture2D(CC_Texture0,v_texCoord);\					   gl_Fragcolor =color*v_fragmentcolor.a;\					   }";CCGLProgram * SmritiShadow::pg=0;voID SmritiShadow::draw(){	onDraw();	CCNode::draw();}voID SmritiShadow::onDraw(){  	struct timeval tv;	gettimeofday(&tv,NulL); 	long ct=tv.tv_sec*1000000+tv.tv_usec;	if(ct-pretime>50000)	{		pretime=ct;		arrcount=0;		for(int i=0;i<20;i+=4)		{			Vertices[i].position[0]=Vertices[i+4].position[0];			Vertices[i].position[1]=Vertices[i+4].position[1];			Vertices[i+1].position[0]=Vertices[i+5].position[0];			Vertices[i+1].position[1]=Vertices[i+5].position[1];			Vertices[i+2].position[0]=Vertices[i+6].position[0];			Vertices[i+2].position[1]=Vertices[i+6].position[1];			Vertices[i+3].position[0]=Vertices[i+7].position[0];			Vertices[i+3].position[1]=Vertices[i+7].position[1];		}		CCSize sz=texture2d->getContentSize();		CCPoint pos=target->getposition();		CCPoint mIDp=pos;		CCSize sz1=target->getContentSize();		bool bfx=target->isFlipX();		bool bfy=target->isFlipY();		CCPoint ap=target->getAnchorPoint();		float rad=CC_degrees_TO_radians(target->getRotation());		pos.x-=sz1.wIDth*ap.x;		pos.y-=sz1.height*ap.y;		float s=sin(-rad);		float c=cos(-rad);		Vertices[20].position[0]=c*pos.x-s*pos.y+(1-c)*mIDp.x+s*mIDp.y;		Vertices[20].position[1]=s*pos.x+c*pos.y-s*mIDp.x+(1-c)*mIDp.y;		Vertices[21].position[0]=c*(pos.x+sz.wIDth)-s*pos.y+(1-c)*mIDp.x+s*mIDp.y;		Vertices[21].position[1]=s*(pos.x+sz.wIDth)+c*pos.y-s*mIDp.x+(1-c)*mIDp.y;		Vertices[22].position[0]=c*pos.x-s*(pos.y+sz.height)+(1-c)*mIDp.x+s*mIDp.y;		Vertices[22].position[1]=s*pos.x+c*(pos.y+sz.height)-s*mIDp.x+(1-c)*mIDp.y;		Vertices[23].position[0]=c*(pos.x+sz.wIDth)-s*(pos.y+sz.height)+(1-c)*mIDp.x+s*mIDp.y;		Vertices[23].position[1]=s*(pos.x+sz.wIDth)+c*(pos.y+sz.height)-s*mIDp.x+(1-c)*mIDp.y;		float tempx=0,tempy=0;		if(bfx)		{			tempx=Vertices[20].position[0];			tempy=Vertices[20].position[1];			Vertices[20].position[0]=Vertices[21].position[0];			Vertices[20].position[1]=Vertices[21].position[1];			Vertices[21].position[0]=tempx;			Vertices[21].position[1]=tempy;			tempx=Vertices[22].position[0];			tempy=Vertices[22].position[1];			Vertices[22].position[0]=Vertices[23].position[0];			Vertices[22].position[1]=Vertices[23].position[1];			Vertices[23].position[0]=tempx;			Vertices[23].position[1]=tempy;		}		if(bfy)		{			tempx=Vertices[20].position[0];			tempy=Vertices[20].position[1];			Vertices[20].position[0]=Vertices[22].position[0];			Vertices[20].position[1]=Vertices[22].position[1];			Vertices[22].position[0]=tempx;			Vertices[22].position[1]=tempy;			tempx=Vertices[21].position[0];			tempy=Vertices[21].position[1];			Vertices[21].position[0]=Vertices[23].position[0];			Vertices[21].position[1]=Vertices[23].position[1];			Vertices[23].position[0]=tempx;			Vertices[23].position[1]=tempy;		}		for(int i=16;i>=0;i-=4)		{			if(Vertices[i].position[0]==Vertices[20].position[0])			{				arrcount+=1;			}		}	}	 	float dst=771,src=1;	glEnable(GL_BLEND);	glBlendFunc(GL_ONE,GL_ONE);	glEnable(GL_DEPTH_TEST);	glDepthFunc(GL_LEQUAL);	pg->use();	pg->setUniformsForBuiltins();	glushort iarr[]={0,1,2,3,0+4,1+4,2+4,3+4,0+8,1+8,2+8,3+8,0+12,1+12,2+12,3+12,0+16,1+16,2+16,3+16};	glBindBuffer(GL_ARRAY_BUFFER,vertexBuffer);	glBufferData(GL_ARRAY_BUFFER,sizeof(Vertex)*20,Vertices,GL_STATIC_DRAW);	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,indexBuffer);	glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(iarr),iarr,GL_STATIC_DRAW);	Glint _positionLocation = glGetAttribLocation(pg->getProgram(),"a_position");	Glint _colorLocation = glGetAttribLocation(pg->getProgram(),"a_color");	Glint _textureLocation = glGetAttribLocation(pg->getProgram(),"a_texCoord");	Glint _textureUniform = glGetUniformlocation(pg->getProgram(),"CC_Texture0");	glEnabLevertexAttribarray(_positionLocation);	glEnabLevertexAttribarray(_colorLocation);	glEnabLevertexAttribarray(_textureLocation);	glVertexAttribPointer(_positionLocation,GL_float,GL_FALSE,sizeof(Vertex),(GLvoID*)offsetof(Vertex,position));	glVertexAttribPointer(_colorLocation,4,color));	glVertexAttribPointer(_textureLocation,TexCoord));	ccGLBindTexture2DN(0,texture2d->getname());	gluniform1i(_textureUniform,0);	glDrawElements(GL_TRIANGLES,sizeof(iarr)/sizeof(glushort)-arrcount*6,GL_UNSIGNED_SHORT,0);	gldisable(GL_DEPTH_TEST);	glBlendFunc(src,dst);	glBindBuffer(GL_ARRAY_BUFFER,0);	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);}SmritiShadow::~SmritiShadow(){	glDeleteBuffers(1,&vertexBuffer);	glDeleteBuffers(1,&indexBuffer);	delete[] Vertices;}voID SmritiShadow::setTarget(CCSprite* spr,CCTexture2D* tex){	target=spr;	texture2d=tex;	CCSize sz=tex->getContentSize();	CCSize sz1=spr->getContentSize();	CCPoint pos=spr->getposition();	CCPoint ap=target->getAnchorPoint();	pos.x-=sz1.wIDth*ap.x;	pos.y-=sz1.height*ap.y;	for(int i=0;i<24;i+=4)	{		Vertices[i].position[0]=pos.x;		Vertices[i].position[1]=pos.y;		Vertices[i].position[2]=0;		Vertices[i+1].position[0]=pos.x+sz.wIDth;		Vertices[i+1].position[1]=pos.y;		Vertices[i+1].position[2]=0;		Vertices[i+2].position[0]=pos.x;		Vertices[i+2].position[1]=pos.y+sz.height;		Vertices[i+2].position[2]=0;		Vertices[i+3].position[0]=pos.x+sz.wIDth;		Vertices[i+3].position[1]=pos.y+sz.height;		Vertices[i+3].position[2]=0;	}}voID SmritiShadow::reset(){	if(pg)	{		pg->reset();		pg->initWithVertexShaderByteArray(vertshader,fragshader);		pg->addAttribute(kCCAttributenameposition,kCCVertexAttrib_position);		pg->addAttribute(kCCAttributenamecolor,kCCVertexAttrib_color);		pg->addAttribute(kCCAttributenameTexCoord,kCCVertexAttrib_TexCoords);		pg->link();		pg->updateUniforms();	}}bool SmritiShadow::init(){	struct timeval tv;	gettimeofday(&tv,NulL); 	long ct=tv.tv_sec*1000000+tv.tv_usec;	pretime=ct;	arrcount=0;	Vertices=new Vertex[4*6];	for(int i=0;i<24;i+=4)	{		Vertices[i].color[3]=0.2*(i/4+1);		Vertices[i].TexCoord[0]=0;		Vertices[i].TexCoord[1]=1;		Vertices[i+1].color[3]=0.2*(i/4+1);		Vertices[i+1].TexCoord[0]=1;		Vertices[i+1].TexCoord[1]=1;		Vertices[i+2].color[3]=0.2*(i/4+1);		Vertices[i+2].TexCoord[0]=0;		Vertices[i+2].TexCoord[1]=0;		Vertices[i+3].color[3]=0.2*(i/4+1);		Vertices[i+3].TexCoord[0]=1;		Vertices[i+3].TexCoord[1]=0;	}	glGenBuffers( 1,&vertexBuffer );	glGenBuffers( 1,&indexBuffer );	texture2d=0;	target=0; 	if(pg==0)	{		pg=new CCGLProgram();		pg->initWithVertexShaderByteArray(vertshader,fragshader);		pg->link();		pg->updateUniforms();	}	return true;}voID ContactListener::BeginContact(b2Contact* contact){	b2Body* bodyA = contact->GetFixtureA()->Getbody();	b2Body* bodyB = contact->GetFixtureB()->Getbody();	CCSprite* spriteA = (CCSprite*)bodyA->GetUserData();	CCSprite* spriteB = (CCSprite*)bodyB->GetUserData();	if((int)spriteA==1)	{		int tag=spriteB->getTag()-500;		int tag1=spriteB->getTag()-600;		if((tag>=2&&tag<=4)||(tag1>=1&&tag1<=7))		{			std::vector<b2Body*>::iterator iter=std::find(Scatter::gthis->m_bodIEs.begin(),Scatter::gthis->m_bodIEs.end(),bodyB);			if(iter==Scatter::gthis->m_bodIEs.end())			  Scatter::gthis->m_bodIEs.push_back(bodyB);		}	}	if((int)spriteB==1)	{		int tag=spriteA->getTag()-500;		int tag1=spriteA->getTag()-600;		if((tag>=2&&tag<=4)||(tag1>=1&&tag1<=7))		{			std::vector<b2Body*>::iterator iter=std::find(Scatter::gthis->m_bodIEs.begin(),bodyA);			if(iter==Scatter::gthis->m_bodIEs.end())			  Scatter::gthis->m_bodIEs.push_back(bodyA);		}	}}voID ContactListener::EndContact(b2Contact* contact){}Scatter* Scatter::gthis=0;voID Scatter::draw(){	CCNode::draw();	onDraw();}voID Scatter::onDraw(){    }voID Scatter::addNewSpriteWithCoords(CCPoint p){	std::string name;	char sname[32];	int rd=rand()%4+1;	sprintf(sname,"fruit%d",rd);	name=sname;	CCSprite *sprite = CCSprite::create((name+".png").c_str());	p.x+=xoff; 	sprite->setposition(p);	sprite->setTag(500+rd);	addChild(sprite);	b2BodyDef bodyDef;	bodyDef.type = b2_dynamicBody;	bodyDef.position.Set(p.x/32.0,p.y/32.0);	bodyDef.userData = sprite;	b2Body *body = m_world->CreateBody(&bodyDef);	GB2ShapeCache *sc = GB2ShapeCache::sharedGB2ShapeCache();	sc->addFixturesToBody(body,sname); 	sprite->setAnchorPoint(sc->anchorPointForShape(sname));	b2Vec2 wd=body->GetWorldCenter();	body->SetAngulardamPing(1.5);	int dr=1;	dr=p.x<480+xoff?1:-1;	body->ApplylinearImpulse(b2Vec2(dr*(10*m_level+rand()%10),2+rand()%10),b2Vec2(wd.x-0.1,wd.y+0.2));}voID Scatter::addBullet(int dr){	char sname[32];	int rd=rand()%6+1;	sprintf(sname,"tool%d",rd);	std::string name=sname;	name=name+".png";	CCSprite *sprite = CCSprite::create(name.c_str());	float x=0,px=0;	if(dr==1)	{		x=-140;		px=20*m_level;		sprite->setFlipX(true);	}	else  	{		x=1100;		px=-20*m_level;	}	float vh=10+rand()%290;	if(rd==6||rd==7)	{		vh=0;	}	sprite->setTag(600+rd);	CCPoint p=ccp(x,250+vh);	sprite->setposition(p);	addChild(sprite,1);    SmritiShadow* pp=SmritiShadow::create();	char tname[32];	sprintf(tname,"tool%d_s.png",rd);	pp->setTarget(sprite,CCTextureCache::sharedTextureCache()->textureForKey(tname));	pp->setTag(10);	addChild(pp);	m_tars.insert(std::map<CCSprite*,CCNode*>::value_type(sprite,pp));	b2BodyDef bodyDef;	bodyDef.type = b2_dynamicBody;	bodyDef.position.Set((p.x+xoff)/32.0,p.y/32.0);	bodyDef.userData = sprite;	b2Body *body = m_world->CreateBody(&bodyDef);	GB2ShapeCache *sc = GB2ShapeCache::sharedGB2ShapeCache();	sc->addFixturesToBody(body,sname); 	sprite->setAnchorPoint(sc->anchorPointForShape(sname));	b2Fixture*  bf=body->GetFixtureList();	while(bf)	{		bf->SetSensor(true);		bf=bf->GetNext();	}	px*=body->GetMass();	b2Vec2 wd=body->GetWorldCenter();	body->SetGravityScale(0);	body->SetAngulardamPing(1.0);	body->ApplylinearImpulse(b2Vec2(px,-(vh/570.0)*abs(px)),b2Vec2(wd.x-0.2,wd.y+0.2));}voID Scatter::setdifficulty(float df){	m_level=df;}voID Scatter::actionOver(CCObject* node,voID* param){	CCNode* snode=(CCNode*)node;	snode->removeFromParentAndCleanup(true);}voID Scatter::porr(){	if(ispause==0)	{		unscheduleUpdate();		ispause=1;	}	else	{		scheduleUpdate();		ispause=0;	}}voID Scatter::setHitct(int ct){   m_hitct=ct;}voID Scatter::attackhandle(b2Body* b){	CCSprite* myActor = (CCSprite*)b->GetUserData();	int tag=myActor->getTag();	float ax=myActor->getpositionX();	CCRect rc1=myActor->boundingBox();	CCRect rc2 =hero->boundingBox();	rc2=CCRect(rc2.origin.x-rc2.size.wIDth/3,rc2.origin.y,rc2.size.wIDth*(1.0+2.0/3.0),rc2.size.height);	//int dis=ccpdistance(hero->getposition(),myActor->getposition());	if(((attackpoint.x>480&&b->GetlinearVeLocity().x<0)||(attackpoint.x<480&&b->GetlinearVeLocity().x>0))&&((tag>600))&&rc1.intersectsRect(rc2))	{		status=2;		b->SetGravityScale(5);		b2Vec2 wd=b->GetWorldCenter();		struct timeval Now;		gettimeofday(&Now,NulL);		srand(Now.tv_sec*1000000+Now.tv_usec);		b2Vec2 bm=b->GetlinearVeLocity();		int dr=1;		if(bm.x>0) dr=-1;		b->ApplylinearImpulse(b2Vec2(dr*(80+rand()%20),20+rand()%70),wd.y+0.2));		b2Fixture*  bf=b->GetFixtureList();		while(bf)		{			bf->SetSensor(false);			bf=bf->GetNext();		}		tag=tag-600;		if(tag>3)			myActor->setTag(0);		attackdelay=0;		GameSound::getGameSound()->PlaySoundsEffect(sound_hero_hero_hit1);		char effectname[100];		if(EnterStageDataExchange::getInstance()->m_chaID==1)		{			CCArmatureDataManager::sharedArmatureDataManager()->addArmaturefileInfo("export/robot_hurt_effects/gx20.png","export/robot_hurt_effects/gx20.pList","export/robot_hurt_effects/gx2.ExportJson");			sprintf(effectname,"gx2");		}		else if(EnterStageDataExchange::getInstance()->m_chaID==2)		{			CCArmatureDataManager::sharedArmatureDataManager()->addArmaturefileInfo("export/kaka_effects/gx100.png","export/kaka_effects/gx100.pList","export/kaka_effects/gx10.ExportJson");			sprintf(effectname,"gx10");		}		else if(EnterStageDataExchange::getInstance()->m_chaID==3)		{			sprintf(effectname,"gx2");		}		else if(EnterStageDataExchange::getInstance()->m_chaID==4)		{			CCArmatureDataManager::sharedArmatureDataManager()->addArmaturefileInfo("export/bruece_effects/ef070.png","export/bruece_effects/ef070.pList","export/bruece_effects/ef07.ExportJson");			sprintf(effectname,"ef07");		}			//	CCArmatureDataManager::sharedArmatureDataManager()->addArmaturefileInfo("export/robot_hurt_effects/gx20.png","export/robot_hurt_effects/gx2.ExportJson");		cocos2d::extension::CCArmature *armature = NulL;		armature = cocos2d::extension::CCArmature::create(effectname);		armature->getAnimation()->playByIndex(0);		ccBlendFunc blend1;		blend1.src = GL_ONE; //GL_ONE,GL_DST_Alpha;GL_ONE_MINUS_DST_Alpha		blend1.dst = GL_ONE;//GL_ZERO;//GL_ONE_MINUS_SRC_Alpha;		armature->setBlendFunc(blend1);		armature->setposition(ccp(hero->getpositionX()+70,hero->getpositionY()+100));		 		if(EnterStageDataExchange::getInstance()->m_chaID!=4)		{	 	armature->setScale(2.0);		}		else		{		 armature->setScale(1.0);		}		 long rate_tag=10;		 switch(tag)		 {		 case  1:			 rate_tag=10;			 break;		 case  2:			 rate_tag=10;			 break;		 case 3:			 rate_tag=15;			 break;		 case  4:			 rate_tag=10;			 break;		 case 5:			 rate_tag=10;			 break;		 case 6:			 rate_tag=20;			 break;		 default:			  rate_tag=10;			 break;		 }		bool Is_addblood=GameLogic::getGameLogic()->GetRandrate(rate_tag);		CCPoint skpos;		SuckBlood* suck=NulL;		if(Is_addblood)		{	      suck=SuckBlood::create(this);		 skpos=ccp(480+60,hero->getpositionY()+110);		suck->runAction(CCSequence::create(CCDelayTime::create(1),CCRemoveSelf::create(true),0));	 		long addblood=random_range(5,15);		long curhp=hero->GetHeroHP()+addblood;		if(curhp>m_s->m_hero_HP)		{			curhp=m_s->m_hero_HP;		}		hero->SetHeroHP(curhp);		}		if(attackpoint.x<480)		{			skpos.x=480-60;			if(EnterStageDataExchange::getInstance()->m_chaID!=4)			{				armature->setScale(-2.0);			}			else			{				armature->setScale(-1.0);			}			armature->setRotation(120);			armature->setposition(ccp(hero->getpositionX()-70,hero->getpositionY()+100));		//	armature->setScale(-2.0);				}		this->addChild(armature,25);		if(Is_addblood)		suck->PlaySuck(skpos,ccp(480,230));		armature->getAnimation()->setMovementEventCallFunc(getParent(),movementEvent_selector(GameLayer::CCArmatureEndEventCall));		++m_curhitcount;		++m_combomnum;		UpdateLevelData();//更新关卡数据		if(m_curhitcount>=m_hitct&&isover==0)		{			isover=1;			if(m_wsc)				((m_pSelector->*m_wsc))();		}	}}voID Scatter::touchhandle(CCPoint curpt){	if(isover||ispause||status==1)		return ;	status=1;	attackdelay=0.3;	attackpoint=curpt;	hero->AttackType();	if(curpt.x<480)	{		hero->setFlipX(true);	}	else		hero->setFlipX(false);}voID Scatter::setoverListener(CCObject* pSelectorTarget,SEL_CallFunc fail){	m_pSelector=pSelectorTarget;	m_wsc=win;	m_fsc=fail;}voID Scatter::setoff(float x){	xoff+=x;}voID Scatter::update(float dt){	struct timeval Now;	gettimeofday(&Now,NulL);	long curtime=Now.tv_sec*1000000+Now.tv_usec;	if(isover==0&&curtime-pretime>700000*(1.0/m_level))	{		if(rand()%2)		{			if(rand()%50>25)				addBullet(1);		}		else		{			if(rand()%50>25)				addBullet(3);		}		pretime=curtime;	}	if(isover==0&&curtime-pretimef>500000*(1.0/m_levelf))	{		if(rand()%3==1)		{			addNewSpriteWithCoords(CCPoint(rand()%200-200,400));		}		else if(rand()%3==2)		{			addNewSpriteWithCoords(CCPoint(rand()%200+960,400));		}		pretimef=curtime;	}		m_world->Step(0.0166670084,8,1);//0.0166670084	mindis=10000;	if(attackdelay>0)	{		attackdelay-=dt;		if(attackdelay<=0)			status=0;	}	for (b2Body* b = m_world->GetbodyList(); b; b = b->GetNext())	{		if (b->GetUserData() != NulL) {			//Synchronize the AtlasSprites position and rotation with the corresponding body			CCSprite* myActor = (CCSprite*)b->GetUserData();			if((int)myActor==1) continue;			if(attackdelay>0.1)			{				attackhandle(b);			}			myActor->setposition( CCPointMake( b->Getposition().x * 32.0-xoff,b->Getposition().y * 32.0) );			if(b->GetlinearVeLocity().x!=0)			{				float ang=-1 * CC_radians_TO_degrees(b->GetAngle()) ;				myActor->setRotation(ang);			}			int tag=myActor->getTag();			float ax=myActor->getpositionX();			if((tag>600))			{				float temp=abs(myActor->getpositionX()-480);				if(temp<abs(mindis))				{					mindis=myActor->getpositionX()-480;				}				//float dis=ccpdistance(hero->getposition(),myActor->getposition());				CCRect rc=hero->boundingBox();				rc=CCRect(rc.origin.x+rc.size.wIDth*2.0/5.0,rc.origin.y,rc.size.wIDth*(1.0-4.0/5.0),rc.size.height);				CCRect rc1=myActor->boundingBox();				float gscale=b->GetGravityScale();				if(gscale!=5&&rc.intersectsRect(rc1))				{					std::vector<b2Body*>::iterator iter=std::find(Scatter::gthis->m_bodIEs.begin(),b);					if(iter==Scatter::gthis->m_bodIEs.end())					{						cocos2d::extension::CCArmature *armature = NulL;						armature = cocos2d::extension::CCArmature::create("djgx");						armature->getAnimation()->playByIndex(0);						ccBlendFunc blend1;						blend1.src = GL_ONE; //GL_ONE,GL_DST_Alpha;GL_ONE_MINUS_DST_Alpha						blend1.dst = GL_ONE;//GL_ZERO;//GL_ONE_MINUS_SRC_Alpha;						armature->setBlendFunc(blend1);						armature->setRotation(-80);						armature->getAnimation()->setMovementEventCallFunc(this,movementEvent_selector(GameLayer::CCArmatureEndEventCall));						this->addChild(armature);						if(b->GetlinearVeLocity().x>0)//左边						{						     hero->setFlipX(true);							armature->setposition(ccp(hero->getpositionX()+20,hero->getpositionY()+70));					        m_herohurttimes++;//主角受伤次数						}						else if(b->GetlinearVeLocity().x<0)//右边						{						hero->setFlipX(false);		 						armature->setposition(ccp(hero->getpositionX()+60,hero->getpositionY()+70));						 						   m_herohurttimes++;//主角受伤次数					 						 						}						//受击                       						myActor->setTag(0);						m_bodIEs.push_back(b);						if(isover==0)						{							if(m_combomnum>m_maxcombom)							{								m_maxcombom=m_combomnum;							}							m_combomnum=0;							int tID=tag-600;							hero->hurtWithdamage(hurts[tID-1],3);							float sct=((float)hero->GetHeroHP())/((float)m_s->m_hero_HP);							m_s->_gameLayer->m_st->m_rate=sct;							if(hero->GetHeroHP()<=0)//失败							{								isover=1;								if(m_fsc)									((m_pSelector->*m_fsc))();							}						}					}				}			}			float acty=myActor->getpositionY();			if(b->IsAwake()==false||acty<-100)			{				std::vector<b2Body*>::iterator iter=std::find(Scatter::gthis->m_bodIEs.begin(),b);				if(iter==Scatter::gthis->m_bodIEs.end())				  m_bodIEs.push_back(b);			}		}		}	std::vector<b2Body*>::iterator iter=m_bodIEs.begin();	for(;iter!=m_bodIEs.end();iter++)	{		CCSprite* myActor = (CCSprite*)(*iter)->GetUserData();				std::map<CCSprite*,CCNode*>::iterator siter=m_tars.find(myActor);		if(siter!=m_tars.end())		{           siter->second->removeFromParentAndCleanup(true);		   m_tars.erase(siter);		}		int tag=myActor->getTag()-500;		int tag1=myActor->getTag()-600;		if(((tag>=2&&tag<=4)||(tag1>=1&&tag1<=3)))		{			if((*iter)->GetlinearVeLocity().x!=0)			{				char name[32];				if(myActor->getTag()>600)				{					sprintf(name,"tool%d_1.png",tag1);				}				else					sprintf(name,"fruit%d_1.png",tag);				(*iter)->SetGravityScale(0);				(*iter)->SetlinearVeLocity(b2Vec2(0,0));				(*iter)->SetAngularVeLocity(0);				b2Fixture*  bf=(*iter)->GetFixtureList();				while(bf)				{					bf->SetSensor(true);					bf=bf->GetNext();				}				CCTexture2D *tex=CCTextureCache::sharedTextureCache()->textureForKey(name);				CCSize sz=tex->getContentSize();				myActor->setTexture(tex);				myActor->setTextureRect(CCRect(0,sz.wIDth,sz.height));				myActor->setRotation(0);				myActor->runAction(CCSequence::create(CCDelayTime::create(3.0),CCCallFuncND::create(this,callfuncND_selector(Scatter::delayremove),0),0));			}		}		else		{			m_world->DestroyBody(*iter);		    myActor->removeFromParentAndCleanup(true);		}	}	m_bodIEs.clear();}voID Scatter::delayremove(CCNode* node,voID* param){	node->setTag(0);	//node->removeFromParentAndCleanup(true);}Scatter::~Scatter(){	delete m_world;	delete contactListener;}voID Scatter::reset(){	isover=0;	hero->IDle();	Hero_Property hero_Property;	long addblood=Game::GetInstance()->GetAddBloodNum();    hero_Property.m_nhero_HP=EnterStageDataExchange::getInstance()->m_hp+addblood; //读取数值表血量	//hero_Property.m_nhero_HP=10; //读取数值表血量	hero->SetHerProperty(hero_Property);}bool Scatter::init(){	m_killemenynum=0;	m_levelscore=0;	m_herohurttimes=0;	m_goldNum=0;	m_maxcombom=m_combomnum=0;	m_perfectnum=0;	m_greatenum=0;	for(int i=0;i<7;++i)	{		hurts[i]=1;	}	gthis=this;	mindis=0;	status=0;	speed=0.5;	m_wsc=0;	attackdelay=0;	m_fsc=0;	m_levelf=m_level=1.0;	m_curhitcount=0;	m_hitct=10;	xoff=0;	isover=0;	ispause=0;	CCTextureCache::sharedTextureCache()->addImage("fruit2_1.png");	CCTextureCache::sharedTextureCache()->addImage("fruit3_1.png");	CCTextureCache::sharedTextureCache()->addImage("fruit4_1.png");	CCTextureCache::sharedTextureCache()->addImage("tool1_1.png");	CCTextureCache::sharedTextureCache()->addImage("tool2_1.png");	CCTextureCache::sharedTextureCache()->addImage("tool3_1.png");	char name[32];	for(int i=0;i<7;++i)	{		sprintf(name,i+1);		CCTextureCache::sharedTextureCache()->addImage(name);	}	long type=rand()%4;	//角色创建选择	switch(EnterStageDataExchange::getInstance()->m_chaID)		//switch(3)	{	case  1:		hero = Hero4::create();  //苏文		break;	case 2:		hero = Hero3::create();  //卡卡西		break;	case  3:		hero = Hero::create(); //女忍者		break;	case  4:		hero = Hero2::create(); //李小龙		break;	default:		hero = Hero::create();		break;	}	hero->setposition(CCPoint(480,170));	hero->IDle();	long daojuItemNum[10]={0};	for(int i=0;i<=4;i++)	{		daojuItemNum[i+1]=CArchive::GetInstance()->GetheronewV11PropertyInfo(i,1);	}	long skill_hp=0;	if(daojuItemNum[2]>=1)//获得30点血量	{		skill_hp=30;	} 	Hero_Property hero_Property;	long addblood=Game::GetInstance()->GetAddBloodNum(); 	hero_Property.m_nhero_HP=EnterStageDataExchange::getInstance()->m_hp+addblood+skill_hp; //读取数值表血量//	hero_Property.m_nhero_HP=10; //读取数值表血量	hero->SetHerProperty(hero_Property);	addChild(hero,10);	struct timeval Now;	gettimeofday(&Now,NulL);	pretimef=pretime=Now.tv_sec*1000000+Now.tv_usec;	b2Vec2 gravity;	gravity.Set(0.0f,-10.0f);	m_world = new b2World(gravity);	contactListener = new ContactListener;	m_world->SetContactListener(contactListener);	m_world->SetAllowSleePing(true);	m_world->SetContinuousPhysics(true);	{		b2BodyDef bd;		b2Body* m_ground = m_world->CreateBody(&bd); 		m_ground->SetUserData((voID*)1);		b2EdgeShape shape;		shape.Set(b2Vec2(-150000.0f/32.0,170.0/32.0),b2Vec2((960.0f+150000.0)/32.0,170.0/32.0));		m_ground->CreateFixture(&shape,0.0f);		shape.Set(b2Vec2(-150000.0f/32.0,900.0/32.0),900.0/32.0));		m_ground->CreateFixture(&shape,0.0f);/*		shape.Set(b2Vec2(-15000.0/32.0,b2Vec2(-15000.0/32.0,900.0/32));		m_ground->CreateFixture(&shape,0.0f);		shape.Set(b2Vec2((960.0+15000.0)/32,b2Vec2((960.0+15000.0)/32,0.0f);*/	}	scheduleUpdate();	GB2ShapeCache::sharedGB2ShapeCache()->addShapesWithfile("sdefs.pList");	return true;}voID Scatter::UpdateLevelData()//更新关卡分数和敌人数目{	m_killemenynum=m_curhitcount;	m_levelscore+=1000;	m_goldNum+=100;	m_combomnum++;   	 	PlayEffects();}voID Scatter::PlayEffects(){	 	CCArmatureDataManager::sharedArmatureDataManager()->addArmaturefileInfo("export/enemy_kill_anim/perfect0.png","export/enemy_kill_anim/perfect0.pList","export/enemy_kill_anim/perfect.ExportJson");	CCSize winsize=CCDirector::sharedDirector()->getWinSize();	if(hero->isFlipX()==false)	{		cocos2d::extension::CCArmature *armature = NulL;		armature = cocos2d::extension::CCArmature::create("perfect");		armature->getAnimation()->playByIndex(0);		long rand1=random_range(1,2);		if(rand1==1)		{			 m_perfectnum++;			armature->getAnimation()->play("Animation1");		}		else		{			m_greatenum++;			armature->getAnimation()->play("Animation2");		}		//	armature->getAnimation()->play("Animation1");		long rand_posx=random_range(100,120);		long rand_posy=random_range(65,100);		armature->setposition(ccp(winsize.wIDth/2+rand_posx,winsize.height/2+rand_posy));		addChild(armature,25);		armature->getAnimation()->setMovementEventCallFunc(this,movementEvent_selector(GameLayer::CCArmatureEndEventCall));	}	else if(hero->isFlipX()==true)	{		cocos2d::extension::CCArmature *armature = NulL;		armature = cocos2d::extension::CCArmature::create("perfect");		armature->getAnimation()->playByIndex(0);		long rand1=random_range(1,2);		if(rand1==1)		{			 m_perfectnum++;			armature->getAnimation()->play("Animation1");		}		else		{					m_greatenum++;			armature->getAnimation()->play("Animation2");		}		long rand_posx=random_range(100,100);		armature->setposition(ccp(winsize.wIDth/2-rand_posx,movementEvent_selector(GameLayer::CCArmatureEndEventCall));	}}
总结

以上是内存溢出为你收集整理的cocos2dx 打武器玩法实现全部内容,希望文章能够帮你解决cocos2dx 打武器玩法实现所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1060933.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存