这节我们来学习Cocos2d-x的最后一节。怎样处理重力感应事件。移植到Android后加入再按一次返回键退出游戏等。我这里用的Android。IOS不会也没设备呃

效果图不好弄,由于是要移植到真机上的。

  1. #ifndef __HELLOWORLD_SCENE_H__
  2. #define __HELLOWORLD_SCENE_H__
  3.  
  4. #include "cocos2d.h"
  5. using namespace cocos2d;
  6. class HelloWorld : public cocos2d::CCLayer
  7. {
  8. public:
  9. // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
  10. virtual bool init();
  11.  
  12. // there's no 'id' in cpp, so we recommend returning the class instance pointer
  13. static cocos2d::CCScene* scene();
  14. //重力感应事件
  15. virtual void didAccelerate(CCAcceleration* pAccelerationValue);
  16. //返回button
  17. virtual void keyBackClicked();
  18. // implement the "static node()" method manually
  19. CREATE_FUNC(HelloWorld);
  20. };
  21.  
  22. #endif // __HELLOWORLD_SCENE_H__

这里重写了两个方法

我们都知道CCLayer是继承了重力感应事件和触屏事件,button事件的

  1. #include "HelloWorldScene.h"
  2.  
  3. #define FIX_POS(_pos, _min, _max) \
  4. if (_pos < _min) \
  5. _pos = _min; \
  6. else if (_pos > _max) \
  7. _pos = _max; \
  8.  
  9. USING_NS_CC;
  10.  
  11. CCScene* HelloWorld::scene()
  12. {
  13. // 'scene' is an autorelease object
  14. CCScene *scene = CCScene::create();
  15.  
  16. // 'layer' is an autorelease object
  17. HelloWorld *layer = HelloWorld::create();
  18.  
  19. // add layer as a child to scene
  20. scene->addChild(layer);
  21.  
  22. // return the scene
  23. return scene;
  24. }
  25.  
  26. // on "init" you need to initialize your instance
  27. bool HelloWorld::init()
  28. {
  29. //////////////////////////////
  30. // 1. super init first
  31. if ( !CCLayer::init() )
  32. {
  33. return false;
  34. }
  35. this->setAccelerometerEnabled(true);
  36. this->setKeypadEnabled(true);
  37.  
  38. CCSize visibleSize= CCDirector::sharedDirector()->getVisibleSize();
  39. CCLabelTTF *lable= CCLabelTTF::create("AccelerometerTest","Arial",34);
  40. lable->setPosition(ccp(visibleSize.width/2,visibleSize.height-50));
  41. this->addChild(lable,0,0);
  42.  
  43. CCSprite *pSprite= CCSprite::create("ball.png");
  44. pSprite->setPosition(ccp(visibleSize.width/2,visibleSize.height/2));
  45. this->addChild(pSprite,0,1);
  46. return true;
  47. }
  48. void HelloWorld::didAccelerate(CCAcceleration* pAccelerationValue)
  49. {
  50. CCObject *pObjectlable= this->getChildByTag(0);
  51. if (pObjectlable==NULL)
  52. {
  53. return;
  54. }
  55. CCLabelTTF *lable=(CCLabelTTF*)pObjectlable;
  56. std::ostringstream strstream;
  57. strstream<<"X:"<<pAccelerationValue->x<<" Y:"<<pAccelerationValue->y<<" Z:"<<pAccelerationValue->z;
  58. std::string str=strstream.str();
  59. lable->setString(str.c_str());
  60.  
  61. //改变小球位置
  62. CCObject *pObjectSprite= this->getChildByTag(1);
  63. if (pObjectSprite==NULL)
  64. {
  65. return;
  66. }
  67. CCSprite *pSprite=(CCSprite*)pObjectSprite;
  68. CCSize pSpriteSize= pSprite->getContentSize();
  69.  
  70. CCPoint ptNow = pSprite->getPosition();
  71. CCPoint ptTemp=CCDirector::sharedDirector()->convertToUI(ptNow);
  72. ptTemp.x += pAccelerationValue->x * 9.81f;
  73. ptTemp.y -= pAccelerationValue->y * 9.81f;
  74. CCPoint ptNext = CCDirector::sharedDirector()->convertToGL(ptTemp);
  75.  
  76. CCSize visibleSize= CCDirector::sharedDirector()->getVisibleSize();
  77. FIX_POS(ptNext.x, (pSpriteSize.width / 2.0), (visibleSize.width - pSpriteSize.width / 2.0));
  78. FIX_POS(ptNext.y, (pSpriteSize.height / 2.0), (visibleSize.height - pSpriteSize.height / 2.0));
  79. pSprite->setPosition(ptNext);
  80.  
  81. }
  82. void HelloWorld::keyBackClicked()
  83. {
  84. }

源文件代码如上,

init中我们创建了一个lable和小球的精灵

通过setAccelerometerEnabled启用重力感应事件

这里能够看下源代码,比触屏事件简单多了。

然后重写重力感应事件。这里我再事件中改动了CCLableTTF的文本。

改变小球的位置

改动文本就不多说了,非常easy,我们主要来看看怎样改变小球位置的

首先我们获得小球精灵

得到精灵位置

转换为UIKIT

这里*9.81f我也不知道什么意思,TestCpp这么写我也就这么写了

为了小球不超出手机屏幕,所以我们写了一个宏  FIX_POS

这里看看就懂了

OK,

我们移植到Android,看看效果,怎么移植。第一节专门介绍了的

效果不错,可是我们按返回键它没有退出游戏,没不论什么反应。

我们在src下的org.cocos2dx.lib中找到Cocos2dxGLSurfaceView.java打开

找到

  1. @Override
  2. public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
  3. switch (pKeyCode) {
  4. case KeyEvent.KEYCODE_BACK:
  5. return false;//这里是自己新增的, 返回false
  6. case KeyEvent.KEYCODE_MENU:
  7. this.queueEvent(new Runnable() {
  8. @Override
  9. public void run() {
  10. Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyDown(pKeyCode);
  11. }
  12. });
  13. return true;
  14. default:
  15. return super.onKeyDown(pKeyCode, pKeyEvent);
  16. }
  17. }

然后我们在自己的java文件里重写onKeyDown,

详细代码例如以下

  1. /****************************************************************************
  2. Copyright (c) 2010-2011 cocos2d-x.org
  3.  
  4. http://www.cocos2d-x.org
  5.  
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12.  
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15.  
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. THE SOFTWARE.
  23. ****************************************************************************/
  24. package com.huc.test;
  25.  
  26. import org.cocos2dx.lib.Cocos2dxActivity;
  27. import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
  28.  
  29. import android.os.Bundle;
  30. import android.view.KeyEvent;
  31. import android.widget.Toast;
  32.  
  33. public class test20140521 extends Cocos2dxActivity{
  34. private long mExitTime;
  35. protected void onCreate(Bundle savedInstanceState){
  36. super.onCreate(savedInstanceState);
  37. }
  38. @Override
  39. public boolean onKeyDown(int keyCode, KeyEvent event) {
  40. // TODO Auto-generated method stub
  41. if (keyCode == KeyEvent.KEYCODE_BACK) {
  42. if ((System.currentTimeMillis() - mExitTime) > 2000) {// 假设两次按键时间间隔大于2000毫秒,则不退出
  43. Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
  44. mExitTime = System.currentTimeMillis();// 更新mExitTime
  45.  
  46. } else {
  47. System.exit(0);// 否则退出程序
  48.  
  49. }
  50. return true;
  51. }
  52. return super.onKeyDown(keyCode, event);
  53. }
  54. public Cocos2dxGLSurfaceView onCreateView() {
  55. Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
  56. // test20140521 should create stencil buffer
  57. glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
  58.  
  59. return glSurfaceView;
  60. }
  61.  
  62. static {
  63. System.loadLibrary("cocos2dcpp");
  64. }
  65. }

OK。试试吧。。。

附源代码和APK

Cocos2D-X2.2.3学习笔记9(处理重力感应事件,移植到Android加入两次返回退出游戏效果)的更多相关文章

  1. jQuery学习笔记之DOM操作、事件绑定(2)

    jQuery学习笔记之DOM操作.事件绑定(2) --------------------学习目录------------------------ 4.DOM操作 5.事件绑定 源码地址: https ...

  2. Cocos2d-x 3.2 学习笔记(九)EventDispatcher事件分发机制

    EventDispatcher事件分发机制先创建事件,注册到事件管理中心_eventDispatcher,通过发布事件得到响应进行回调,完成事件流. 有五种不同的事件机制:EventListenerT ...

  3. Android开发学习笔记--给一个按钮定义事件

    学习Android的第一天,了解了各种布局,然后自己动手画出了一个按钮,然后给按钮定义了一个事件是弹出一条消息显示“我成功了!”字样,具体过程如下: 1.修改布局文件activity_main.xml ...

  4. Android学习笔记--处理UI事件

    Handling UI Events 在Android里, 有不只一种方式可以截获用户与你的应用程序交互的事件. 在你的界面上处理事件时,你需要捕获用户与某个View实例交互时所产生的事件.View类 ...

  5. Java基础学习笔记十二 类、抽象类、接口作为方法参数和返回值以及常用API

    不同修饰符使用细节 常用来修饰类.方法.变量的修饰符 public 权限修饰符,公共访问, 类,方法,成员变量 protected 权限修饰符,受保护访问, 方法,成员变量 默认什么也不写 也是一种权 ...

  6. C#线程学习笔记五:线程同步--事件构造

    本笔记摘抄自:https://www.cnblogs.com/zhili/archive/2012/07/23/Event_Constructor.html,记录一下学习过程以备后续查用. 前面讲的线 ...

  7. C#学习笔记--详解委托,事件与回调函数

    .Net编程中最经常用的元素,事件必然是其中之一.无论在ASP.NET还是WINFrom开发中,窗体加载(Load),绘制(Paint),初始化(Init)等等.“protected void Pag ...

  8. 《C#高级编程》学习笔记------C#中的委托和事件(续)

    本文转载自张子阳 目录 为什么要使用事件而不是委托变量? 为什么委托定义的返回值通常都为void? 如何让事件只允许一个客户订阅?(事件访问器) 获得多个返回值与异常处理 委托中订阅者方法超时的处理 ...

  9. python学习笔记10(函数一): 函数使用、调用、返回值

    一.函数的定义 在某些编程语言当中,函数声明和函数定义是区分开的(在这些编程语言当中函数声明和函数定义可以出现在不同的文件中,比如C语言),但是在Python中,函数声明和函数定义是视为一体的.在Py ...

随机推荐

  1. 新手须知设计的法则 Mark

    经常看到一些讲如何学习设计的文章,坦白讲感觉有些千篇一律.且不痛不痒,都说要看点书.学点画.练软件.多观察……唉,练软件这事还要说么,难道你还需要告诉一个人学开发是需要学习编程语言的? 学习是基于过往 ...

  2. 从 Page not found: / 提示说起,我是怎么发现webstrom与myeclipse冲突问题及解决的

    #从 Page not found: / 提示说起,我是怎么发现webstrom与myeclipse冲突问题的 ##  从前面发表了两篇博文,[webstorm+nodejs+JetBrains ID ...

  3. iframe和frame的区别

    在同时有frame和Iframe的一个窗口里frame最大可以做个frameset的儿子,Iframe最大也只能做到frameset的孙子.frame的布局限于几种,Iframe想放哪里放哪里.fra ...

  4. NServiceBus教程-持久化

    NServiceBus的各种特性需要持久性.其中有超时.传奇和订阅存储. 四个持久化技术在NServiceBus在使用: RavenDB nHibernate 内存中 MSMQ 读到安装Raven D ...

  5. CSStickyHeaderFlowLayout collectionView headerView 悬浮

    github:https://github.com/levyleo/CSStickyHeaderFlowLayout iOS 10 使用时会出现崩溃:https://github.com/CSStic ...

  6. postsharp初体验

    首先,有必要先介绍下,什么叫做AOP(Aspect-Oriented Programming,面向切面编程).下图是百度的词条解释 用图来解释可能更直接了当些: ps:图片来自http://www.c ...

  7. 第二百二十八天 how can I 坚持

    hibernate 还有好多不会搞啊,本来很简单的东西,没用过就不会. 今天... 只是感觉很累,昨天爬山爬的,不知道该写点啥了,买的羽绒服到了,还行吧,凑合穿吧. 睡觉了.今天貌似又发脾气了.哎.. ...

  8. 转】Mahout学习路线图

    原博文出自于: http://blog.fens.me/hadoop-mahout-roadmap/ 感谢! Mahout学习路线图 Hadoop家族系列文章,主要介绍Hadoop家族产品,常用的项目 ...

  9. reentrant可重入函数

    在多任务操作系统环境中,应用程序的各个任务是并发运行的,所以会经常出现多个任务“同时”调用同一个函数的情况.这里之所以在“同时” 这个词上使用了引号,是因为这个歌”同时“的含义与我们平时所说的同时不是 ...

  10. Leetcode226:Invert Binary Tree

    Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 /** * Definition for a ...