发现问题:update()函数不能用virtual前缀
主:
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);
}
}