cocos 2dx 3.12 学习笔记(五) BallTest

来源:互联网 发布:木工材料计算软件 编辑:程序博客网 时间:2024/09/21 06:33

一个小球,开始的时候从屏幕中心发出,在碰到场景边界的时候改变方向。


BallTestLayer.h

#ifndef __BALL_TEST_LAYER_H__#define __BALL_TEST_LAYER_H__#include "cocos2d.h"USING_NS_CC;class BallTest : public cocos2d::Layer{public :static cocos2d::Scene * createScene();public:CREATE_FUNC(BallTest);virtual bool init();void UpdateBall(float dt);//次方法使用计时器 <span style="font-family: Arial, Helvetica, sans-serif;">schedule</span>private:cocos2d::Sprite * m_pSprite = nullptr;        cocos2d::Sprite * m_pTestSprite = nullptr;cocos2d::Vec2 m_speed = cocos2d::Vec2::ZERO;   //定义一个m_speed作为小球运动时候得速度。};#endif

BallTestLayer.cpp


#include "BallTestLayer.h"Scene * BallTest::createScene(){auto scene = Scene::create();auto layer = BallTest::create();scene->addChild(layer);return scene;}bool BallTest::init(){if (!Layer::init()){return false;}m_speed = Vec2(2.0f,2.0f);auto size = this->getContentSize();float x = 0;float y = 0;x = size.width / 2;y = size.height / 2;m_pSprite = Sprite::create("CloseNormal.png"); //使用了  CloseNormal作为小球。没有制作新的素材this->addChild(m_pSprite);m_pSprite->setPosition(Vec2(x, y)); schedule(schedule_selector(BallTest::UpdateBall),0.01f);return true;}void BallTest::UpdateBall(float dt){auto size = this->getContentSize();Vec2 pos = m_pSprite->getPosition();auto ballSizex = m_pSprite->getContentSize().width;auto ballSizey = m_pSprite->getContentSize().height;//Vec2 speed = m_speed;     此处不能使用局部变量。if (pos.x <= 0 + ballSizex / 2 || pos.x >= size.width - ballSizex / 2){m_speed.x = -m_speed.x;}if (pos.y <= 0 + ballSizex / 2 || pos.y >= size.height - ballSizex / 2){m_speed.y = -m_speed.y;}pos.x += m_speed.x;pos.y += m_speed.y;m_pSprite->setPosition(pos);}




0 0
原创粉丝点击