加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Cocos2d-3.x_基本数据类型(cocos2d::Vector)

发布时间:2020-12-14 21:03:56 所属栏目:百科 来源:网络整理
导读:#ifndef __BALL_H_INCLUDE__#define __BALL_H_INCLUDE__#include "cocos2d.h"USING_NS_CC;class Ball : public cocos2d::Sprite{public:virtual bool init();void move();CREATE_FUNC(Ball);private:float positionX;float positionY;};#endif #include "Bal
#ifndef __BALL_H_INCLUDE__
#define __BALL_H_INCLUDE__

#include "cocos2d.h"

USING_NS_CC;

class Ball : public cocos2d::Sprite
{
public:
	virtual bool init();

	void move();

	CREATE_FUNC(Ball);

private:
	float positionX;
	float positionY;
};

#endif
#include "Ball.h"

bool Ball::init()
{
	if (!Sprite::initWithFile("ball.png"))
	{
		return false;
	}

	positionX = CCRANDOM_0_1() * 10 - 5;
	positionY = CCRANDOM_0_1() * 10 - 5;

	return true;
}

void Ball::move()
{
	this->setPosition(Vec2(this->getPositionX() + positionX,this->getPositionY() + positionY));
}
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"
#include "Ball.h"

USING_NS_CC;


class HelloWorld : public cocos2d::Layer
{
public:
    static cocos2d::Scene* createScene();

    virtual bool init();

	virtual void update(float dt);

	void addBall(float dt);

    CREATE_FUNC(HelloWorld);

private:
	cocos2d::Vector<Ball *> balls;
};

#endif // __HELLOWORLD_SCENE_H__
#include "HelloWorldScene.h"

Scene* HelloWorld::createScene()
{
    auto scene = Scene::create();
    auto layer = HelloWorld::create();
    scene->addChild(layer);

    return scene;
}

bool HelloWorld::init()
{
    if ( !Layer::init() )
    {
        return false;
    }
    
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

	this->schedule(schedule_selector(HelloWorld::addBall),0.1f);

	this->scheduleUpdate();

    return true;
}

void HelloWorld::addBall(float dt)
{
	Size visibleSize = Director::getInstance()->getVisibleSize();

	Ball *ball = Ball::create();
	ball->setPosition(Vec2(visibleSize.width / 2.0,visibleSize.height / 2.0));
	this->addChild(ball);

	balls.pushBack(ball);
}

void HelloWorld::update(float dt)
{
	Size visibleSize = Director::getInstance()->getVisibleSize();

	Ball *ball = NULL;
	for (auto iter = balls.begin(); iter != balls.end(); iter ++)
	{
		ball = *iter;
		ball->move();

		if (ball->getPositionX() > visibleSize.width ||
			ball->getPositionX() < 0 ||
			ball->getPositionY() > visibleSize.height ||
			ball->getPositionY() < 0)
		{
			balls.eraSEObject(ball);
			ball->removeFromParentAndCleanup(true);
			ball = NULL;
			break;
		}
	}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读