搜索
查看: 867|回复: 0
打印 上一主题 下一主题

【cocos2d-x】边界弹回

[复制链接]
跳转到指定楼层
楼主
发表于 2016-5-26 02:17:19 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
资源图片:


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


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

广播台
特别关注
快速回复 返回顶部 返回列表