#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);