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

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

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


#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"
using namespace cocos2d;
class HelloWorld : public cocos2d::CCLayer
{
public:
    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();  

    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::CCScene* scene();
    //重力感应事件
	virtual void didAccelerate(CCAcceleration* pAccelerationValue);
	//返回按钮
	 virtual void keyBackClicked();
    // implement the "static node()" method manually
    CREATE_FUNC(HelloWorld);
};

#endif // __HELLOWORLD_SCENE_H__

这里重写了两个方法

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

#include "HelloWorldScene.h"


#define FIX_POS(_pos, _min, _max) \
    if (_pos < _min)        \
    _pos = _min;        \
else if (_pos > _max)   \
    _pos = _max;        \

USING_NS_CC;

CCScene* HelloWorld::scene()
{
	// 'scene' is an autorelease object
	CCScene *scene = CCScene::create();

	// 'layer' is an autorelease object
	HelloWorld *layer = HelloWorld::create();

	// add layer as a child to scene
	scene->addChild(layer);

	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
	//
	// 1. super init first
	if ( !CCLayer::init() )
	{
		return false;
	}
	this->setAccelerometerEnabled(true);
	this->setKeypadEnabled(true);

	CCSize visibleSize= CCDirector::sharedDirector()->getVisibleSize();
	CCLabelTTF *lable= CCLabelTTF::create("AccelerometerTest","Arial",34);
	lable->setPosition(ccp(visibleSize.width/2,visibleSize.height-50));
	this->addChild(lable,0,0);


	CCSprite *pSprite= CCSprite::create("ball.png");
	pSprite->setPosition(ccp(visibleSize.width/2,visibleSize.height/2));
	this->addChild(pSprite,0,1);
	return true;
}
void HelloWorld::didAccelerate(CCAcceleration* pAccelerationValue)
{
	CCObject *pObjectlable= this->getChildByTag(0);
	if (pObjectlable==NULL)
	{
		return;
	}
	CCLabelTTF *lable=(CCLabelTTF*)pObjectlable;
	std::ostringstream strstream;
	strstream<<"X:"<<pAccelerationValue->x<<"  Y:"<<pAccelerationValue->y<<"  Z:"<<pAccelerationValue->z;
	std::string str=strstream.str();
	lable->setString(str.c_str());


	//改变小球位置
	CCObject *pObjectSprite= this->getChildByTag(1);
	if (pObjectSprite==NULL)
	{
		return;
	}
	CCSprite *pSprite=(CCSprite*)pObjectSprite;
	CCSize pSpriteSize= pSprite->getContentSize();

	CCPoint ptNow  = pSprite->getPosition();
	CCPoint ptTemp=CCDirector::sharedDirector()->convertToUI(ptNow);
	ptTemp.x += pAccelerationValue->x * 9.81f;
	ptTemp.y -= pAccelerationValue->y * 9.81f;
	CCPoint ptNext = CCDirector::sharedDirector()->convertToGL(ptTemp);

	CCSize visibleSize= CCDirector::sharedDirector()->getVisibleSize();
	FIX_POS(ptNext.x, (pSpriteSize.width / 2.0), (visibleSize.width - pSpriteSize.width / 2.0));
	FIX_POS(ptNext.y, (pSpriteSize.height / 2.0), (visibleSize.height - pSpriteSize.height / 2.0));
	pSprite->setPosition(ptNext);

}
void HelloWorld::keyBackClicked()
{
}

源文件代码如上,

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

通过setAccelerometerEnabled启用重力感应事件

这里可以看下源码,比触屏事件简单多了,

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

改变小球的位置

修改文本就不多说了,很简单,我们主要来看看如何改变小球位置的


首先我们获得小球精灵

得到精灵位置

转换为UIKIT

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

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

这里看看就懂了


OK,

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


效果不错,但是我们按返回键它没有退出游戏,没任何反应,

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

找到

@Override
	public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
		switch (pKeyCode) {
			case KeyEvent.KEYCODE_BACK:	
				return false;//这里是自己新增的, 返回false
			case KeyEvent.KEYCODE_MENU:
				this.queueEvent(new Runnable() {
					@Override
					public void run() {
						Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyDown(pKeyCode);
					}
				});
				return true;
			default:
				return super.onKeyDown(pKeyCode, pKeyEvent);
		}
	}
然后我们在自己的java文件中重写onKeyDown,

具体代码如下

/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package com.huc.test;

import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

public class test20140521 extends Cocos2dxActivity{
	private long mExitTime;
    protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);	
	}
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	// TODO Auto-generated method stub
    	 if (keyCode == KeyEvent.KEYCODE_BACK) {  
             if ((System.currentTimeMillis() - mExitTime) > 2000) {// 如果两次按键时间间隔大于2000毫秒,则不退出  
                 Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();  
                 mExitTime = System.currentTimeMillis();// 更新mExitTime  
   
             } else {  
                 System.exit(0);// 否则退出程序  
   
             }  
             return true;  
         }  
    	return super.onKeyDown(keyCode, event);
    }
    public Cocos2dxGLSurfaceView onCreateView() {
    	Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
    	// test20140521 should create stencil buffer
    	glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
    	
    	return glSurfaceView;
    }

    static {
        System.loadLibrary("cocos2dcpp");
    }     
}
OK,试试吧。。。


附源码和APK

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值