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

完成此项目的方法有很多种,我来分享我最近学到的一种方法。
首先就是构造一个类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
}

效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值