cocos2d-x 2.X demo学习笔记 9 ----Touches 触摸事件 以及碰撞检测

#include "Ball.h"
#include "Paddle.h"


Ball::Ball(void)
{
}


Ball::~Ball(void)
{
}

//球的半径
float Ball::radius()
{
    return getTexture()->getContentSize().width / 2;
}

//球的创建 参数的一个纹理
Ball* Ball::ballWithTexture(CCTexture2D* aTexture)
{
    Ball* pBall = new Ball();
    pBall->initWithTexture(aTexture);
    pBall->autorelease();


    return pBall;
}


void Ball::move(float delta)
{
    CCSize size = CCDirector::sharedDirector()->getWinSize();


    this->setPosition( ccpAdd(getPosition(), ccpMult(m_velocity, delta)) );
    
    if (getPosition().x > size.width - radius()) 
    {
        setPosition( ccp( size.width - radius(), getPosition().y) );
        m_velocity.x *= -1;
    } 
    else if (getPosition().x < radius()) 
    {
        setPosition( ccp(radius(), getPosition().y) );
        m_velocity.x *= -1;
    }
}


void Ball::collideWithPaddle(Paddle* paddle)

{

    //获取矩形区域

    CCRect paddleRect = paddle->rect();

    //起点的位置

    paddleRect.origin.x += paddle->getPosition().x;
    paddleRect.origin.y += paddle->getPosition().y;
    //获取相应的 底部位置,中间位置,下边缘位置
    float lowY  = paddleRect.getMinY();
    float midY  = paddleRect.getMidY();
    float highY = paddleRect.getMaxY();
    //获取左右边缘
    float leftX  = paddleRect.getMinX();
    float rightX = paddleRect.getMaxX();
    
    if (getPosition().x > leftX && getPosition().x < rightX) {
     //第一个没有击中
        bool hit = false;
        float angleOffset = 0.0f; 
        //集中侧面
        if (getPosition().y > midY && getPosition().y <= highY + radius()) 
        {
            setPosition( CCPointMake(getPosition().x, highY + radius()) );
            hit = true;
            angleOffset = (float)M_PI / 2;
        }
        else if (getPosition().y < midY && getPosition().y >= lowY - radius()) 

        {

//正式击中

            setPosition( CCPointMake(getPosition().x, lowY - radius()) );
            hit = true;
            angleOffset = -(float)M_PI / 2;
        }
        
        if (hit) 
        {//集中后的反应
            float hitAngle = ccpToAngle(ccpSub(paddle->getPosition(), getPosition())) + angleOffset;
            
            float scalarVelocity = ccpLength(m_velocity) * 1.05f;
            float velocityAngle = -ccpToAngle(m_velocity) + 0.5f * hitAngle;
            
            m_velocity = ccpMult(ccpForAngle(velocityAngle), scalarVelocity);
        }
    }    

class Paddle : public CCSprite, public CCTargetedTouchDelegate 牌子的声明,声明如此后一定要添加进触屏事件

 CCDirector* pDirector = CCDirector::sharedDirector();
    pDirector->getTouchDispatcher()->addTargetedDelegate(this, 0, true);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值