Cocos2d-x   发布时间:2022-05-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了cocos2dx - 伤害实现大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

http://www.cnblogs.com/straTrail/p/5065911.html

本节主要讲如何通过创建简单的矩形区域来造成伤害

  在小游戏中简单的碰撞需求应用box2d等引擎会显得过于臃肿复杂,且功能不是根据需求定制,还要封装,为此本节讲述一下如何自己实现简单的碰撞,来达到伤害效果。

这里先看下效果图:

一、定义小组类别

  定义如下:

// 组别mask @H_616_52@enum enGroupMask { GROUP_NONE = 0x0000,GROUP_PLAYER = 0x0001:rgb(0,GROUP_MONSTER = 0x0002:rgb(0,};

  用二进制位来定义小组,方便后面判断用位快速判断。

二、定义CBody类用于碰撞实现

  代码如下:

#ifndef __CBody_H__
@H_616_52@#define __CBody_H__
#include "IGameDef.h"
#include cocos2d.h"
@H_616_52@#define DRAW_BODY 1
#ifdef DRAW_BODY 
#include GLES-Render.h#endif

USING_NS_Cc;
@H_616_52@class CBody : @H_616_52@public Node
{
@H_616_52@public:
    // implement the "static create()" method manually
    CREATE_FUNC(CBody);

    @H_616_52@virtual @H_616_52@bool init();

    @H_616_52@void SetRect(@H_616_52@float x,@H_616_52@float y,255); line-height:1.5!important">float w,255); line-height:1.5!important">float h){ m_cRect = Rect(x,y,w,h); }

    @H_616_52@void SetGroupMask(enGroupMask nGroupMask){ m_nGroupMask = nGroupMask; }

    enGroupMask GetGroupMask() @H_616_52@const{ @H_616_52@return m_nGroupMask; }

    enGroupMask CanContactGroup() @H_616_52@const;

    判断是否可以碰撞该类别
    @H_616_52@bool IsGroupCanContact(enGroupMask nGroupMask)  @H_616_52@const Rect GetRect()  判断矩形是否交叉
    @H_616_52@bool IntersectsRect(@H_616_52@const Rect& rect)  @H_616_52@void SetContactCallBACk(@H_616_52@const std::function<@H_616_52@void(CBody*)>& callBACk){ m_constactFunc = callBACk; }

     碰撞回调函数
    @H_616_52@void OnContact(CBody* pBody);


     绘制矩形区域
#ifdef DRAW_BODY 
    @H_616_52@void draw(Renderer *renderer,255); line-height:1.5!important">const Mat4& transform,uint32_t flags);
    @H_616_52@virtual    @H_616_52@void onDraw(@H_616_52@const Mat4 &transform,uint32_t flags);
@H_616_52@#endif

@H_616_52@private:

    CBody();
    ~CBody();

#ifdef DRAW_BODY 
    Customcatommand m_pCustomcatommand;
    b2Draw* m_debugDraw;
@H_616_52@#endif
     
    Rect m_cRect;

    std::function<@H_616_52@void(CBody*)> m_constactFunc;

    enGroupMask        m_nGroupMask;
};


@H_616_52@#endif __CBody_H__

关键实现有以下几个:

  1、用位快速判断是否可以产生碰撞

@H_616_52@@H_616_52@bool CBody::IsGroupCanContact(enGroupMask nGroupMask)  const { @H_616_52@return nGroupMask&CanContactGroup(); }

  2、获取矩形实际的坐标,利用cocos2dx矩形相交判断方法,判断重叠

const Rect CBody::GetRect() constVec2& pt =this->convertToWorldSpace(@H_616_52@this->getPosition()); @H_616_52@return Rect(pt.x + m_cRect.origin.x,pt.y + m_cRect.origin.y,m_cRect.size.width,m_cRect.size.height); } @H_616_52@ bool CBody::IntersectsRect(@H_616_52@const Rect& rect) @H_616_52@const { @H_616_52@return GetRect().intersectsRect(rect); }

  3、将创建的CBody类添加到管理中vector的实例@H_586_83@m_vBody管理

CBody::~CBody() { CBattleMgr::geTinstance()->EreaseBody(@H_616_52@this); @H_616_52@#ifdef DRAW_BODY @H_616_52@if (m_debugDraw) { @H_616_52@delete m_debugDraw; m_debugDraw = NULL; } @H_616_52@#endif } @H_616_52@bool CBody::init() { @H_616_52@#ifdef DRAW_BODY m_debugDraw = @H_616_52@new GLESDebugDraw(1.0); @H_616_52@#endif CBattleMgr::geTinstance()->InsertBody(@H_616_52@this); @H_616_52@return @H_616_52@true; }

  同时每帧在管理类中的update进行碰撞判断如下:

void CBattleMgr::update(@H_616_52@float dt) { @H_616_52@while (m_vBody.size()>0) { size_t nLast = m_vBody.size() - 1; CBody* pBody = m_vBodY[nLast]; m_vBody.pop_BACk(); @H_616_52@if (pBody) { m_vSwapBody.push_BACk(pBody); @H_616_52@for (size_t i = 0; i < nLast; ++i) { CBody* pTempBody = m_vBodY[i]; @H_616_52@if (pTempBody ) { @H_616_52@bool hurt1 = pTempBody->IsGroupCanContact(pBody->GetGroupMask()); @H_616_52@bool hurt2 = pBody->IsGroupCanContact(pTempBody->GetGroupMask()); @H_616_52@if ((hurt1 || hurt2)&&pTempBody->IntersectsRect(pBody->GetRect())) { @H_616_52@if (hurt1) { pTempBody->OnContact(pBody); } @H_616_52@if (hurt2) { pBody->OnContact(pTempBody); } } } } } } m_vSwapBody.swap(m_vBody); }

  上述代码通过2个vector管理CBody,在update时进行一次判断碰撞并调用OnContact方法。

  4、为了方便显示上图的灰色矩形框需要用以下的类进行显示图形

/*
* Copyright (C) 2006-2007 Erin Catto http://www.gphysics.com
*
* iPhone port by Simon Oliver - http://www.simonoliver.com - http://www.handcircus.com
*
* This software is provided 'as-is',without any express or implied
* warranty.  In no event will the authors be Held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,* including commercial applications,and to alter it and redistribute it
* freely,subject to the following reStrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product,an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such,and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source diStribution.
*/

#ifndef RENDER_H
@H_616_52@#define RENDER_H

#include Box2D/Box2D.h"

@H_616_52@struct b2AABB;

 This class implements debug drawing callBACks that are invoked
 inside b2World::Step.
@H_616_52@class GLESDebugDraw : @H_616_52@public b2Draw
{
    float32 mRatio;
    cocos2d::GLProgram* mShaderProgram;
    GLint        mColorLOCATIOn;

    @H_616_52@void initShader( @H_616_52@void );
@H_616_52@public:
    GLESDebugDraw();

    GLESDebugDraw( float32 ratio );

    @H_616_52@void DrawPolygon(@H_616_52@const b2Vec2* vertices,255); line-height:1.5!important">int vertexCount,255); line-height:1.5!important">const b2Color& color);

    @H_616_52@void DrawSolidPolygon(@H_616_52@void DrawCircle(@H_616_52@const b2Vec2& center,float32 radius,255); line-height:1.5!important">void DrawSolidCircle(@H_616_52@const b2Vec2& axis,255); line-height:1.5!important">void DrawSegment(@H_616_52@const b2Vec2& p1,255); line-height:1.5!important">const b2Vec2& p2,255); line-height:1.5!important">void DrawTransform(@H_616_52@const b2Transform& xf);

    @H_616_52@void DrawPoint(@H_616_52@const b2Vec2& p,float32 size,255); line-height:1.5!important">void DrawString(@H_616_52@int x,255); line-height:1.5!important">int y,255); line-height:1.5!important">char* @H_616_52@String,...); 

    @H_616_52@void DrawAABB(b2AABB* aabb,255); line-height:1.5!important">const b2Color& color);
};


@H_616_52@#endif

 * Copyright (C) 2006-2007 Erin Catto 
 *
 * iPhone port by Simon Oliver - 
 *
 * This software is provided 'as-is',without any express or implied
 * warranty.  In no event will the authors be Held liable for any damages
 * arising from the use of this software.
 * Permission is granted to anyone to use this software for any purpose,and to alter it and redistribute it
 * freely,subject to the following reStrictions:
 * 1. The origin of this software must not be misrepresented; you must not
 * claim that you wrote the original software. If you use this software
 * in a product,an acknowledgment in the product documentation would be
 * appreciated but is not required.
 * 2. Altered source versions must be plainly marked as such,and must not be
 * misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source diStribution.
 */

#include "
#include <stdio.h>
#include <stdarg.h>
#include <@H_616_52@String.h>

USING_NS_Cc;

GLESDebugDraw::GLESDebugDraw()
    : mRatio( 1.0f )
{
    @H_616_52@this->initShader();
}

GLESDebugDraw::GLESDebugDraw( float32 ratio )
    : mRatio( ratio )
{
    @H_616_52@this->initShader();
}

@H_616_52@void GLESDebugDraw::initShader( @H_616_52@void )
{
    mShaderProgram = GLProgramCache::geTinstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_U_COLOR);

    mColorLOCATIOn = glGetUniformLOCATIOn( mShaderProgram->getProgram(),u_color");
}

@H_616_52@void GLESDebugDraw::DrawPolygon(@H_616_52@const b2Vec2* old_vertices,255); line-height:1.5!important">const b2Color& color)
{
    mShaderProgram->use();
    mShaderProgram->setUniformsForBuilTins();

    b2Vec2* vertices = @H_616_52@new b2VeC2[vertexCount];
    @H_616_52@for( @H_616_52@int i=0;i<vertexCount;i++) 
    {
        vertices[i] = old_vertices[i];
        vertices[i] *= mRatio;
    }

    mShaderProgram->setUniformLOCATIOnWith4f(mColorLOCATIOn,color.r,color.g,color.b,128); line-height:1.5!important">1);

    glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION,2,GL_FLOAT,GL_falSE,128); line-height:1.5!important">0,vertices);
    glDrawArrays(GL_LINE_LOOP,vertexCount);

    CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,vertexCount);


    checK_GL_ERROR_DEBUG();

    @H_616_52@delete[] vertices;
}

@H_616_52@void GLESDebugDraw::DrawSolidPolygon(0;i<vertexCount;i++) {
        vertices[i] = old_vertices[i];
        vertices[i] *= mRatio;
    }
    
    mShaderProgram->setUniformLOCATIOnWith4f(mColorLOCATIOn,color.r*0.5f,color.g*:rgb(128,color.b*0.5f);

    glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION,vertices);

    glDrawArrays(GL_TRIANGLE_FAN,vertexCount);

    mShaderProgram->setUniformLOCATIOnWith4f(mColorLOCATIOn,128); line-height:1.5!important">1);
    glDrawArrays(GL_LINE_LOOP,vertexCount*2);

    checK_GL_ERROR_DEBUG();

    @H_616_52@void GLESDebugDraw::DrawCircle(@H_616_52@const b2Color& color)
{
    mShaderProgram->use();
    mShaderProgram->setUniformsForBuilTins();

    @H_616_52@const float32 k_segments = 16.0f;
    @H_616_52@int vertexCount=16;
    @H_616_52@const float32 k_increment = 2.0f * b2_pi / k_segments;
    float32 theta = 0.0f;
    
    GLfloat*    glVertices = @H_616_52@new GLfloat[vertexCount*2];
    @H_616_52@int i = 0; i < k_segments; ++i)
    {
        b2Vec2 v = center + radius * b2Vec2(cosf(theta),sinf(theta));
        glVertices[i*2]=v.x * mRatio;
        glVertices[i*2+1]=v.y * mRatio;
        theta += k_increment;
    }
    
    mShaderProgram->setUniformLOCATIOnWith4f(mColorLOCATIOn,128); line-height:1.5!important">1);
    glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION,glVertices);

    glDrawArrays(GL_LINE_LOOP,vertexCount);

    checK_GL_ERROR_DEBUG();

    @H_616_52@delete[] glVertices;
}

@H_616_52@void GLESDebugDraw::DrawSolidCircle(0.5f);
    glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION,glVertices);
    glDrawArrays(GL_TRIANGLE_FAN,vertexCount);


    mShaderProgram->setUniformLOCATIOnWith4f(mColorLOCATIOn,vertexCount);

     Draw the axis line
    DrawSegment(center,center+radius*axis,color);

    CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(void GLESDebugDraw::DrawSegment(@H_616_52@const b2Color& color)
{
    mShaderProgram->use();
    mShaderProgram->setUniformsForBuilTins();

    mShaderProgram->setUniformLOCATIOnWith4f(mColorLOCATIOn,128); line-height:1.5!important">1);

    GLfloat    glVertices[] = 
    {
        p1.x * mRatio,p1.y * mRatio,p2.x * mRatio,p2.y * mRatio
    };
    glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION,glVertices);

    glDrawArrays(GL_LInes,128); line-height:1.5!important">0,128); line-height:1.5!important">2);

    CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,128); line-height:1.5!important">2);

    checK_GL_ERROR_DEBUG();
}

@H_616_52@void GLESDebugDraw::DrawTransform(@H_616_52@const b2Transform& xf)
{
    b2Vec2 p1 = xf.p,p2;
    @H_616_52@const float32 k_axisScale = 0.4f;
    p2 = p1 + k_axisScale * xf.q.GetXAxis();
    DrawSegment(p1,p2,b2Color(0));

    p2 = p1 + k_axisScale * xf.q.GetYAxis();
    DrawSegment(p1,128); line-height:1.5!important">0));
}

@H_616_52@void GLESDebugDraw::DrawPoint(1);

        glPointSize(sizE);

    GLfloat                glVertices[] = {
        p.x * mRatio,p.y * mRatio
    };

    glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION,glVertices);

    glDrawArrays(GL_POINTS,128); line-height:1.5!important">1);
        glPointSize(1.0f);

    CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1);

    checK_GL_ERROR_DEBUG();
}

@H_616_52@void GLESDebugDraw::DrawString(@H_616_52@char *:rgb(0,...)
{
    NSLog(@"DrawString: unsupported: %s",String);
    printf(String);
     Unsupported as yet. Could replace with bitmap font renderer at a later date */
}

@H_616_52@void GLESDebugDraw::DrawAABB(b2AABB* aabb,128); line-height:1.5!important">1);

    GLfloat                glVertices[] = {
        aabb->lowerBound.x * mRatio,aabb->lowerBound.y * mRatio,aabb->upperBound.x * mRatio,aabb->upperBound.y * mRatio,aabb->lowerBound.x * mRatio,aabb->upperBound.y * mRatio
    };

    glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION,glVertices);
    glDrawArrays(GL_LINE_LOOP,128); line-height:1.5!important">4);

    CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(4);

    checK_GL_ERROR_DEBUG();
}

  然后在CBodydraw中做如下处理进行绘制

#ifdef DRAW_BODY 
@H_616_52@void CBody::onDraw(:rgb(0,uint32_t flags)
{

    @H_616_52@if (m_debugDraw)
    {
        b2Vec2 vs[4];
        @H_616_52@const Rect rect = GetRect();
        vs[0].Set(rect.origin.x,rect.origin.y);
        vs[1].Set(rect.origin.x + rect.size.width,128); line-height:1.5!important">2].Set(rect.origin.x + rect.size.width,rect.origin.y + rect.size.height);
        vs[3].Set(rect.origin.x,rect.origin.y + rect.size.height);
        m_debugDraw->DrawSolidPolygon(vs,128); line-height:1.5!important">4,b2Color(0.6f,128); line-height:1.5!important">0.6f));
    }
}
@H_616_52@void CBody::draw(Renderer *renderer,uint32_t flags)
{
    _globalZOrder
    m_pCustomcatommand.init(30);
    m_pCustomcatommand.func = CC_CALLBACK_0(CBody::onDraw,255); line-height:1.5!important">this,transform,flags);
    renderer->addCommand(&@H_390_51@m_pCustomcatommand);
}
@H_616_52@#endif

  5、最后在@H_586_83@monster等实体类init中添加该CBody的实例,即可为其添加碰撞形状。

如下:

        m_pBody = CBody::create();
        m_pBody->SetGroupMask(enGroupMask::GROUP_MONSTER);
        m_pBody->SetRect(-100,-200,128); line-height:1.5!important">200);
        @H_616_52@this->addChild(m_pBody);

三、定义CDamage用于创建伤害

主要实现以下方法:

#ifndef __CDamage_H__
@H_616_52@#define __CDamage_H__
#include Body.h"
#include <@H_616_52@set>
USING_NS_Cc;
@H_616_52@class CDamage : @H_616_52@public Node
{
 implement the "static create()" method manually
    CREATE_FUNC(CDamage);

    @H_616_52@void update(@H_616_52@float dt);

    @H_616_52@float h);

    @H_616_52@void SetGroupMask(enGroupMask nGroupMask);

    @H_616_52@void OnContact(CBody* pBody);
@H_616_52@private:

    CDamage();
    ~CDamage();

    @H_616_52@int m_nDieTime;  伤害区域消失时间
 CBody  *@H_390_51@m_pBody;

    std::@H_616_52@set<CBody*>    m_sContact;
};
@H_616_52@#endif __CDamage_H__

关键点:
  1、m_nDieTime在update中实现控制伤害区域存在时间

  2、m_sContact控制一个CDamage实例对每个实体仅造成一次伤害。

在怪物等攻击动作中添加事件并在事件回调中添加如下代码创建伤害

void CEntity::ActionEvent(Frame *framE) { cocostudio::timeline::EventFrame* evnt = dynamic_cast<cocostudio::timeline::EventFrame*>(framE); @H_616_52@if (!evnt) @H_616_52@return; std::@H_616_52@String str = evnt->getEvent(); @H_616_52@if (str == attack") { auto damage = CDamage::create(); damage->SetRect(-200); damage->SetGroupMask(m_nGroupMask); @H_616_52@if (@H_616_52@this->getScaleX()<0) { damage->setPositionX(-100); } @H_616_52@this->addChild(damagE); } }

添加事件方法,即在特定帧添加以下的帧事件
  

至此游戏的基本元素已经都有了。

剩下的自己可以进行扩展了,如:血量为0时,播放死亡动画,并显示失败等。

  

在怪物死亡创建一个新的怪物:

  

大佬总结

以上是大佬教程为你收集整理的cocos2dx - 伤害实现全部内容,希望文章能够帮你解决cocos2dx - 伤害实现所遇到的程序开发问题。

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
猜你在找的Cocos2d-x相关文章