cocos2d-x2.2.3 Learning note 9 (Handling gravity-sensing events, porting to Android to join two times to return to exit game effects)

Source: Internet
Author: User
Tags addchild

In this section we will learn the last section of Cocos2d-x, how to handle gravity sensing events, porting to Android and then pressing the back button to exit the game. The Android,ios I'm using here don't have any equipment, either.

Not good, because it is to be transplanted to the real machine.


#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 the 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 ();    Gravity-sensing event virtual void Didaccelerate (ccacceleration* paccelerationvalue);//returns button virtual void keybackclicked ();    Implement the "Static node ()" Method manually    Create_func (HelloWorld);}; #endif//__helloworld_scene_h__

Two methods are rewritten here

We all know that Cclayer is inherited from gravity-sensing events and touch-screen events, and the button event

#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 a autorelease objectccscene *scene = Ccscene::create ();//' layer ' is an Autore Lease Objecthelloworld *layer = Helloworld::create ();//Add layer as a child to scenescene->addchild (layer);//Return T He scenereturn scene;} On "Init" need to initialize your Instancebool helloworld::init () {////////////////////////////////1. Super init fi Rstif (! Cclayer::init ()) {return false;} This->setaccelerometerenabled (True); this->setkeypadenabled (true); Ccsize visiblesize= Ccdirector::shareddirector ()->getvisiblesize (); Cclabelttf *lable= cclabelttf::create ("Accelerometertest", "Arial", lable->setposition); VISIBLESIZE.WIDTH/2,VISIBLESIZE.HEIGHT-50)); This->addchild (lable,0,0); Ccsprite *psprite= ccsprite::create ("Ball.png");p sprite->setposition (CCP (VisibLESIZE.WIDTH/2,VISIBLESIZE.HEIGHT/2)); This->addchild (psprite,0,1); return true;} void HelloWorld::d idaccelerate (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 ());//change ball position 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);p ttemp.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));p sprite->setposition (Ptnext);} void helloworld::keybackclicked () {}

Source file code as above,

In Init we created a lable and a small ball of elves

Enabling gravity-sensing events via setaccelerometerenabled

It is much easier to see the source code here than the touch screen event.

Then rewrite the gravity-sensing event, where I changed the Cclablettf text in the event,

Change the position of the ball

Change the text is not much to say, very easy, we mainly look at how to change the position of the ball


First we get the ball elf

Get elf Position

Convert to Uikit

I don't know what that means here, *9.81f, Testcpp, that's what I wrote.

For small balls do not exceed the phone screen. So we wrote a macro fix_pos.

Look here, you'll understand.


Ok.

We transplanted to Android to see how the effect, how to transplant, the first section specifically introduced the


The effect is good, but we press the back button and it does not exit the game. No matter what the reaction,

We found Cocos2dxglsurfaceview.java open in the org.cocos2dx.lib under SRC

Found it

@Overridepublic boolean onKeyDown (final int pkeycode, final keyevent pkeyevent) {switch (pkeycode) {case Keyevent.keycode _back:return false;//Here is your own new, return Falsecase KeyEvent.KEYCODE_MENU:this.queueEvent (new Runnable () {@Overridepublic void Run () {Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyDown (Pkeycode);}}); Return True;default:return Super.onkeydown (Pkeycode, pkeyevent);}}
Then we rewrite the onkeydown in our own Java file,

Detailed code such as the following

/****************************************************************************copyright (c) 2010-2011 Cocos2d-x.orghttp://www.cocos2d-x.orgpermission is hereby granted, free of charge, to all person obtaining a copyof this s  Oftware and associated documentation files (the "Software"), to dealin the software without restriction, including without  Limitation the Rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the software, and To permit persons to whom the software isfurnished to doing so, subject to the following conditions:the above copyright Noti Ce and this permission notice shall being included inall copies or substantial portions of the Software.the software is provi DED "As is", without WARRANTY of any KIND, EXPRESS orimplied, including and not LIMITED to the warranties of Merchantabili Ty,fitness for A particular PURPOSE and noninfringement. In NO EVENT shall theauthors or COPYRIGHT holders is liable for any CLAIM, damages OR otherliability, WHETHERIn a ACTION of contract, TORT or OTHERWISE, arising from,out of or in CONNECTION with the software or the use or other DE Alings inthe 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) {//Assume two times the key time interval is greater than 2000 milliseconds.                   Do not exit Toast.maketext (this, "Press again to exit the program", Toast.length_short). Show (); Mexittime = System.currenttimemillis ();//Update mexittime} ELSE {SYSTEM.EXIT (0);//Exit program} return true;    } return Super.onkeydown (KeyCode, event); 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, try it.

。。


Attached source code and APK

cocos2d-x2.2.3 Learning note 9 (Handling gravity-sensing events, porting to Android to join two times to return to exit game effects)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.