Cocos2d-x实战项目开发:运动的小球

时间:2021-06-04 20:07:53

完成此项目的方法有很多种,我来分享我最近学到的一种方法。
首先就是构造一个类Ball,
Ball.h文件的代码如下:

# include <iostream>
# include "cocos2d.h"
USING_NS_CC;

class Ball :public Sprite
{
public:
virtual bool init();//初始化构造函数
CREATE_FUNC(Ball);
void move();//运动函数
virtual void update(float);
private:
Size visibleSize;
float speedX;//水平速度
float speedY;//竖直速度
};

Ball.cpp.文件代码如下:

# include "Ball.h"
USING_NS_CC;

bool Ball::init()
{
Sprite::initWithFile("ball.png");
visibleSize = Director::getInstance()->getVisibleSize();
speedX = CCRANDOM_0_1() * 50 - 25;
speedY = CCRANDOM_0_1() * 50 - 25;

return true;
}

void Ball::move()
{
scheduleUpdate();
}
void Ball::update(float dt)
{
setPosition(getPositionX()+speedX, getPositionY() + speedY );//利用周期控制位置,控制运动
if (getPositionX() < getContentSize().width / 2)//使小球在显示框内运动
speedX = fabs(speedX);
if (getPositionX() > visibleSize.width - getContentSize().width / 2)
speedX = -fabs(speedX);
if (getPositionY() < getContentSize().width / 2)
speedY = fabs(speedY);
if (getPositionY() > visibleSize.height - getContentSize().width / 2)
speedY = -fabs(speedY);

}

紧接着在HelloWorld.cpp中进行简单导入即可,代码如下:

#include "HelloWorldScene.h"
# include "Ball.h"

USING_NS_CC;

Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();

// 'layer' is an autorelease object
auto layer = HelloWorld::create();

// add layer as a child to scene
scene->addChild(layer);

// return the scene
return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
for (auto i = 0; i < 30; i++)//植入多个小球
{
auto ball = Ball::create();
ball->setPosition(CCRANDOM_0_1()*100+100, CCRANDOM_0_1()*100+100);
addChild(ball);
ball->move();
}

return true;
}


void HelloWorld::menuCloseCallback(Ref* pSender)
{
Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}

Cocos2d-x实战项目开发:运动的小球