创建一个小球类 Ball.h和Ball.cpp
#ifndef __BALL_H__
#define __BALL_H__
#include "cocos2d.h"
class Ball : public cocos2d::Sprite
{
public:
CREATE_FUNC(Ball);
bool init();
//小球移动
void move();
};
#endif // !__BALL_H__
=====================================================
#include "Ball.h"
USING_NS_CC;
bool Ball::init()
{
Sprite::initWithFile("ball.png");
//创建矩形刚体
auto body = PhysicsBody::createCircle(this->getContentSize().width / 2);
//设置弹力
body->getShape(0)->setRestitution(1.02f);
//设置摩擦力
body->getShape(0)->setFriction(0.0f);
//设置是否受力旋转
body->setRotationEnable(false);
//设置是否受重力
body->setGravityEnable(false);
//设置是否静态 静态物体不会因为收到碰撞而改变位置
body->setDynamic(true);
//设置速度上限 放止速度过快后检测不到而飞出屏幕
body->setVelocityLimit(2000);
//把精灵和物理刚体绑定
this->setPhysicsBody(body);
return true;
}
void Ball::move()
{
//随机x偏移量
float x = rand() % 300 + 300;
if (0 == rand() % 2)
{
x = -x;
}
this->getPhysicsBody()->setVelocity(Vect(x, 500));
}
================================================================
在GameScene.h中添加新的变量和方法
Ball *ball = nullptr;
bool isFirstTouch = true;
bool onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *unused_event);
在GameScene.cpp的init方法中 添加新的代码
//创建下方墙壁
auto wallDown = Wall::create("width.png");
wallDown->setPosition(vSize.width * 0.5, wallLeft->getBoundingBox().getMinY() - wallTop->getContentSize().height / 2);
this->addChild(wallDown);
//创建小球
ball = Ball::create();
ball->setPosition(vSize.width / 2, vSize.height * 0.2);
this->addChild(ball);
//触摸事件
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = CC_CALLBACK_2(GameScene::onTouchBegan, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
在触摸事件中
bool GameScene::onTouchBegan(Touch *touch, Event *unused_event)
{
if (isFirstTouch)
{
isFirstTouch = false;
ball->move();
}
return true;
}
运行后点击屏幕 就会看到小球随机运动后在里面碰来碰去了。
这一章内容就先介绍到这里,下一章讲介绍下面墙壁的隐藏和显示,同时隐藏和显示刚体,并放出源代码和资源。