标签:
主:
bool HelloWorld::init()
{
if ( !LayerColor::initWithColor(Color4B(255,255,255,255)))
{
return false;
}
for (int i=0;i<10;i++) {
auto b=Ball::create();
b->setPosition(CCRANDOM_0_1()*200+400,CCRANDOM_0_1()*200+400);
addChild(b);
}
return true;
}
hpp:
#include <stdio.h>
#include "cocos2d.h"
using namespace cocos2d;
class Ball:public Sprite
{
public:
virtual bool init();
void update(float dt);
CREATE_FUNC(Ball);
private:
float speedX,speedY;
Size visibleSize;
};
cpp:
#include "Ball.hpp"
bool Ball::init(){
Sprite::initWithFile("GOODS_3201_0.png");
visibleSize=Director::getInstance()->getVisibleSize();
speedX=CCRANDOM_0_1()*10-5;//-5到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().height/2) {
speedY=fabs(speedY);
}
if (getPositionY()>visibleSize.height-getContentSize().height/2) {
speedY=-fabs(speedY);
}
}
标签:
原文地址:http://www.cnblogs.com/daochong/p/5257060.html