资源图片:
C++代码:
//Ball.h
#ifndef __BALL_H__
#define __BALL_H__
#include "cocos2d.h"
using namespace cocos2d;
class Ball : public Sprite
{
public:
virtual bool init();
virtual void update(float dt);
CREATE_FUNC(Ball);
private:
float speedX,speedY;
Size visibleSize;
};
#endif
//Ball.cpp
#include "Ball.h"
bool Ball::init()
{
Sprite::initWithFile("ball.jpg");
visibleSize = Director::getInstance()->getVisibleSize();
speedX = CCRANDOM_0_1()*10-5;
speedY = CCRANDOM_0_1()*10-5;
scheduleUpdate();
return true;
}
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().height / 2 )
{
speedY = -fabs(speedY);
}
}
//HelloWorldScene.cpp
#include "HelloWorldScene.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "Ball.h"
USING_NS_CC;
using namespace cocostudio::timeline;
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()
{
if (!LayerColor::initWithColor(Color4B(255,255,255,255)))
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
for (int i = 0; i < 30; i++)
{
auto balls = Ball::create();
balls->setPosition(CCRANDOM_0_1()*200+100,CCRANDOM_0_1()*200+100);
addChild(balls);
}
return true;
}
因为程序的背景颜色是白色,HelloWorldScene.h
class HelloWorld : public cocos2d:ayerColor
|