zoukankan      html  css  js  c++  java
  • 【potatoes游戏开发】cocos2dx3.X项目重写(八)观察者模式(中)

    观察者模式中,也可以传递数据。

      void postNotification(const std::string& name, Ref *sender);
    第二个参数就是可以传递的数据,格式是Ref*,如果想传递变量的话要强制转换一下。

    我们要怎样得到这个消息的值呢。

    在订阅函数里

    void __NotificationCenter::addObserver(Ref *target, 
                                           SEL_CallFuncO selector,
                                           const std::string& name,
                                           Ref *sender)
    
    其中第二个参数,也就是回掉函数的定义是这样的

    typedef void (Ref::*SEL_CallFuncO)(Ref*);

    参数是Ref*,也就是传来的消息。
    ················································分割线····················································

    为了方便起见,我把地面和背景分别放在两个layer里面,在跳跃的时候,设置了屏幕跟随,也就是让地面的layer在player跳跃的时候下降,这个下降和上升的距离取决于player跳多高,这里我也给背景layer添加了效果。用观察者给背景layer实时传递player的y坐标。

    在地面layer里

    	   auto playerh= (int)player->getPositionY();
               auto  playerh2 = (Ref*)(playerh);
    	   NotificationCenter::getInstance()->postNotification("h",playerh2);
    在背景layer里面,因为订阅了消息,而player死亡之后要注意取消订阅,否则会有bug

    void bglayer::call(Ref* r)
    {
    	if ((int)r<0)
    	{
    		NotificationCenter::getInstance()->removeAllObservers(this);
    		this->unschedule(schedule_selector(bglayer::run));
    
    	}
    	else
    	{
    		this->setPositionY(this->getPosition().y-((int)r-h)/4);
    		h=(int)r;
    
    	}
    
    }

    这个简单的算法实现了地面,背景和人的呼应,有疑问请留言哦。
  • 相关阅读:
    【css】怎么让Chrome支持小于12px 的文字
    java操作linux,调用shell命令
    20个非常有用的Java程序片段
    Java集合详解
    SVN使用指南
    利用SQL语句查询数据库中所有表
    HttpClient-03Http状态管理
    HttpClient-02连接管理
    HttpClient-01基本概念
    IDEA安装插件
  • 原文地址:https://www.cnblogs.com/Anzhongliu/p/6091829.html
Copyright © 2011-2022 走看看