zoukankan      html  css  js  c++  java
  • Cocos2d入门--3--小球运动

    本章直接上源代码。内容不难,主要就是

    HelloWorldScene.h文件:

     1 #ifndef __HELLOWORLD_SCENE_H__
     2 #define __HELLOWORLD_SCENE_H__
     3 
     4 #include "cocos2d.h"
     5 
     6 class HelloWorld : public cocos2d::Layer
     7 {
     8 protected:
     9     float _angle;
    10     cocos2d::Vec2 _vec;
    11 public:
    12     static cocos2d::Scene* createScene();
    13 
    14     virtual bool init();
    15     
    16     // a selector callback
    17     void menuCloseCallback(cocos2d::Ref* pSender);
    18     
    19     // implement the "static create()" method manually
    20     CREATE_FUNC(HelloWorld);
    21     
    22     virtual void update(float dt);
    23 private:
    24     //获取屏幕可视范围
    25     float width_L;
    26     float width_R;
    27     cocos2d::DrawNode* ball;
    28 };
    29 
    30 #endif // __HELLOWORLD_SCENE_H__

    HelloWorldScene.cpp文件:

     1 // on "init" you need to initialize your instance
     2 bool HelloWorld::init()
     3 {
     4     //////////////////////////////
     5     // 1. super init first
     6     if ( !Layer::init() )
     7     {
     8         return false;
     9     }
    10     
    11     Size visibleSize = Director::getInstance()->getVisibleSize();
    12     Vec2 origin = Director::getInstance()->getVisibleOrigin();
    13     width_L = origin.x;
    14     width_R = origin.x + visibleSize.width;
    15     
    16     ball = DrawNode::create();
    17     ball -> drawDot(Vec2(0, 0), 4, Color4F(1.0f, 1.0f, 1.0f, 1.0f));
    18     
    19     addChild(ball);
    20     ball -> setPosition(origin.x + visibleSize.width/2,origin.y + visibleSize.height/2);
    21     
    22     //action相关的运动我们一般不是用来做游戏的运动,一般用来做游戏的变化效果。因为action不能很好的用来表现出游戏的效果
    23 //    dot -> runAction(RepeatForever::create(MoveBy::create(0.2, _vec*100)));
    24     //
    25     scheduleUpdate();
    26     return true;
    27 }
    28 
    29 void HelloWorld::update(float dt){
    30     ball -> setPositionX(ball->getPositionX()+5);
    31     if (ball->getPositionX()<width_L-ball->getContentSize().width/2
    32         || ball->getPositionX()>width_R+ball->getContentSize().width/2) {
    33         ball->setPositionX(-ball->getContentSize().width/2);
    34     }
    35 }

    然后实现的效果:

     

     
     
  • 相关阅读:
    总结报告的感想
    第14、15週PTA題目的處理
    PTA題目的處理(三)
    PTA题目的處理(四)
    PTA題目的處理(二)
    PTA題目的處理(一)
    國慶和中秋的學習成果
    剛進入大學一個月的總結和作業
    【接口平台】too many values to unpack
    【接口平台】生成静态模拟数据
  • 原文地址:https://www.cnblogs.com/goodboy-heyang/p/4905530.html
Copyright © 2011-2022 走看看