Cocos2dx-based pseudo-stereo menu

Source: Internet
Author: User

Cocos2dx-based pseudo-stereo menu
RotateMenu description final


Next, we will reference the self-chaos westward journey.

Design Description

1. The menu item (MenuItem) is evenly distributed on an elliptical (similar)

2. the long axis of the elliptic is 2/3 width, and the short axis is 2/8 height.

3. Top menu item Scale = 1, opacity = 255, last side Scale = 0.5, opacity = 129. Other positions are implemented according to trigonometric Transformation (in updatePosition)

4. selected)

5. The unit angle (unitAngle) is the number of 2 * PI/menu items

6. Slide a width and rotate the menu in two degrees.

7. When the Touch ends, the position is automatically adjusted to ensure that there are food items at the beginning

8. Moving more than 1/3 angle will be rounded forward

9. If the unit is smaller than 1/6, click the menu.

10. The default menu size is not full screen, but 2/3 of the screen. It is set through Node: setContentSize ().

Use

If you use this menu, you only need to know the two functions.

1. Constructor

RotateMenu: create (CREATE_FUNC)

2. Add MenuItem

Void addMenuItem (cocos2d: MenuItem * item );

Other functions can read the code.

Function settings of related parameters have not been added

Code

Statement

# Ifndef _ ROTA__TE_MENU_H __# define _ ROTA__TE_MENU_H __# include "cocos2d. h "/** simulate the rotation menu of the main interface of the westward journey */class RotateMenu: public cocos2d: Layer {public: // constructor CREATE_FUNC (RotateMenu ); // Add the menu item void addMenuItem (cocos2d: MenuItem * item); // update the position void updatePosition (); // update the position with the animation void updatePositionWithAnimation (); // modify the position correction angle. forward indicates the moving direction. When the value exceeds 1/3, enter 1. // true indicates that the positive value is false. Negative void rectify (bool forward); // initialize virtual bool init (); // The reset operation has the Rotation angle set to 0 void reset (); private: // sets the angle radian void setAngle (float angle); float getAngle (); // set unit angle radian void setUnitAngle (float angle); float getUnitAngle (); // The sliding distance conversion angle. The conversion policy is to move half Menu. width is equal to _ unitAnglefloat disToAngle (float dis); // return the selected itemcocos2d: MenuItem * getCurrentItem (); private: // the menu has been rotated to degrees float _ angle; // menu item set. The order of _ children changes. Create an array and save the order cocos2d: Vector.
 
  
_ Items; // float _ unitAngle in unit angle; // listener function virtual bool onTouchBegan (cocos2d: Touch * touch, cocos2d: Event * event ); virtual void onTouchEnded (cocos2d: Touch * touch, cocos2d: Event * event); virtual void onTouchMoved (cocos2d: Touch * touch, cocos2d: Event * event ); // call the void actionEndCallBack (float dx) function after the animation ends; // the currently selected itemcocos2d: MenuItem * _ selectedItem; // The animation running time float animationDuration = 0.3f ;}; # endif
 

Implementation

# Include "RotateMenu. h" # include
 
  
# Define PI acos (-1) USING_NS_CC; bool RotateMenu: init () {if (! Layer: init () return false; _ angle = 0.0; this-> ignoreAnchorPointForPosition (false); _ selectedItem = nullptr; Size s = Director: getInstance () -> getWinSize (); this-> setContentSize (s/3*2); this-> setAnchorPoint (Vec2 (0.5f, 0.5f); auto listener = EventListenerTouchOneByOne :: create (); listener-> onTouchBegan = CC_CALLBACK_2 (RotateMenu: onTouchBegan, this); listener-> onTouchMoved = CC_CALLBACK_2 (RotateMenu: onTouch Moved, this); listener-> onTouchEnded = CC_CALLBACK_2 (RotateMenu: onTouchEnded, this); getEventDispatcher ()-> listener (listener, this); return true ;}; void RotateMenu:: addMenuItem (cocos2d: MenuItem * item) {item-> setPosition (this-> getContentSize ()/2); this-> addChild (item); _ items. pushBack (item); setUnitAngle (2 * PI/_ items. size (); reset (); updatePositionWithAnimation (); return;} Void RotateMenu: updatePosition () {auto menuSize = getContentSize (); auto disY = menuSize. height/8; auto disX = menuSize. width/3; for (int I = 0; I <_ items. size (); I ++) {float x = menuSize. width/2 + disX * sin (I * _ unitAngle + getAngle (); float y = menuSize. height/2-disY * cos (I * _ unitAngle + getAngle (); _ items. at (I)-> setPosition (Vec2 (x, y); _ items. at (I)-> setZOrder (-(int) y); // Opacity 129 ~ 255_items.at (I)-> setOpacity (192 + 63 * cos (I * _ unitAngle + getAngle (); _ items. at (I)-> setScale (0.75 + 0.25 * cos (I * _ unitAngle + getAngle ();} return;} void RotateMenu: updatePositionWithAnimation () {// stop all possible actions for (int I = 0; I <_ items. size (); I ++) _ items. at (I)-> stopAllActions (); auto menuSize = getContentSize (); auto disY = menuSize. height/8; auto disX = menuSize. width/3; for (int I = 0; I <_ items. Size (); I ++) {float x = menuSize. width/2 + disX * sin (I * _ unitAngle + getAngle (); float y = menuSize. height/2-disY * cos (I * _ unitAngle + getAngle (); auto moveTo = MoveTo: create (animationDuration, Vec2 (x, y); _ items. at (I)-> runAction (moveTo); // Opacity 129 ~ 255 auto fadeTo = FadeTo: create (animationDuration, (192 + 63 * cos (I * _ unitAngle + getAngle (); _ items. at (I)-> runAction (fadeTo); // The scaling ratio is 0.5 ~ 1 auto scaleTo = ScaleTo: create (animationDuration, 0.75 + 0.25 * cos (I * _ unitAngle + getAngle (); _ items. at (I)-> runAction (scaleTo); _ items. at (I)-> setZOrder (-(int) y);} scheduleOnce (schedule_selector (RotateMenu: actionEndCallBack), animationDuration); return;} void RotateMenu: reset () {_ angle = 0;} void RotateMenu: setAngle (float angle) {this-> _ angle = angle;} float RotateMenu: getAngle () {return _ angle ;} void RotateMenu: setUnitAngle (float angle) {_ unitAngle = angle;} float RotateMenu: getUnitAngle () {return _ unitAngle;} float RotateMenu: disToAngle (float dis) {float width = this-> getContentSize (). width/2; return dis/width * getUnitAngle ();} MenuItem * RotateMenu: getCurrentItem () {if (_ items. size () = 0) return nullptr; // actually add 0.1 getAngle () here to prevent loss of precision int index = (int) (2 * PI-getAngle ()/getUnitAngle () + 0.1 * getUnitAngle (); index % = _ items. size (); return _ items. at (index);} bool RotateMenu: onTouchBegan (Touch * touch, Event * event) {// stop all possible actions first for (int I = 0; I <_ items. size (); I ++) _ items. at (I)-> stopAllActions (); if (_ selectedItem) _ selectedItem-> unselected (); auto position = this-> convertToNodeSpace (touch-> getLocation ()); auto size = this-> getContentSize (); auto rect = Rect (0, 0, size. width, size. height); if (rect. containsPoint (position) {return true;} return false;} void RotateMenu: onTouchEnded (Touch * touch, Event * event) {auto xDelta = touch-> getLocation (). x-touch-> getStartLocation (). x; rectify (xDelta> 0); if (disToAngle (fabs (xDelta ))
  
   
Activate (); updatePositionWithAnimation (); return;} void RotateMenu: onTouchMoved (Touch * touch, Event * event) {auto angle = disToAngle (touch-> getDelta (). x); setAngle (getAngle () + angle); updatePosition (); return;} void RotateMenu: rectify (bool forward) {auto angle = getAngle (); while (angle <0) angle + = PI * 2; while (angle> PI * 2) angle-= PI * 2; if (forward> 0) angle = (int) (angle + getUnitAngle ()/3*2)/getUnitAngle () * getUnitAngle (); elseangle = (int) (angle + getUnitAngle ()/3) /getUnitAngle () * getUnitAngle (); setAngle (angle);} void RotateMenu: actionEndCallBack (float dx) {_ selectedItem = getCurrentItem (); if (_ selectedItem) _ selectedItem-> selected ();}
  
 

A bad Demo

Statement

#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include "cocos2d.h"class HelloWorld : public cocos2d::Layer{public:    // there's no 'id' in cpp, so we recommend returning the class instance pointer    static cocos2d::Scene* createScene();    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone    virtual bool init();         // a selector callback    void menuCloseCallback(cocos2d::Ref* pSender);void menuItem1Callback(cocos2d::Ref* pSender);void menuItem2Callback(cocos2d::Ref* pSender);void menuItem3Callback(cocos2d::Ref* pSender);void menuItem4Callback(cocos2d::Ref* pSender);void menuItem5Callback(cocos2d::Ref* pSender);void hideAllSprite();cocos2d::Sprite *sprite[5];      // implement the "static create()" method manually    CREATE_FUNC(HelloWorld);};#endif // __HELLOWORLD_SCENE_H__

Statement

#include "HelloWorldScene.h"#include "RotateMenu.h"USING_NS_CC;typedef struct SceneList{const char *name;std::function
 
   callback;}SceneList;SceneList sceneList[] = {{ "Demo1", [](){return HelloWorld::createScene(); } }};const unsigned int sceneCount = sizeof(sceneList) / sizeof(SceneList);#define LINE_SPACE 40Scene* HelloWorld::createScene(){    // 'scene' is an autorelease object    auto scene = Scene::create();        // 'layer' is an autorelease object    auto 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 instancebool HelloWorld::init(){    //////////////////////////////    // 1. super init first    if ( !Layer::init() )    {        return false;    }        Size visibleSize = Director::getInstance()->getVisibleSize();    Vec2 origin = Director::getInstance()->getVisibleOrigin();    /////////////////////////////    // 2. add a menu item with "X" image, which is clicked to quit the program    //    you may modify it.    // add a "close" icon to exit the progress. it's an autorelease object    auto closeItem = MenuItemImage::create(                                           "CloseNormal.png",                                           "CloseSelected.png",                                           CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));    closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,                                origin.y + closeItem->getContentSize().height/2));   //  create menu, it's an autorelease object  /*  auto menu = Menu::create(closeItem, NULL);    menu->setPosition(Vec2::ZERO);    this->addChild(menu, 1);*/auto item1 = MenuItemImage::create("Demo1/item1_1.png", "Demo1/item1_0.png", CC_CALLBACK_1(HelloWorld::menuItem1Callback, this));auto item2 = MenuItemImage::create("Demo1/item2_1.png", "Demo1/item2_0.png", CC_CALLBACK_1(HelloWorld::menuItem2Callback, this));auto item3 = MenuItemImage::create("Demo1/item3_1.png", "Demo1/item3_0.png", CC_CALLBACK_1(HelloWorld::menuItem3Callback, this));auto item4 = MenuItemImage::create("Demo1/item4_1.png", "Demo1/item4_0.png", CC_CALLBACK_1(HelloWorld::menuItem4Callback, this));auto item5 = MenuItemImage::create("Demo1/item5_1.png", "Demo1/item5_0.png", CC_CALLBACK_1(HelloWorld::menuItem5Callback, this));RotateMenu *menu = RotateMenu::create();menu->addMenuItem(item1);menu->addMenuItem(item2);menu->addMenuItem(item3);menu->addMenuItem(item4);menu->addMenuItem(item5);menu->setPosition(visibleSize/2);this->addChild(menu, 2);for (int i = 0; i < 5; i++){char str[20];sprintf(str, "Demo1/item%d.jpg", i + 1);sprite[i] = Sprite::create(str);sprite[i]->setAnchorPoint(Vec2(0.5f, 0.5f));sprite[i]->setPosition(visibleSize / 2);this->addChild(sprite[i]);}hideAllSprite();    /////////////////////////////    // 3. add your codes below...    // add a label shows "Hello World"    // create and initialize a label        auto label = LabelTTF::create("Hello World", "Arial", 24);        // position the label on the center of the screen    label->setPosition(Vec2(origin.x + visibleSize.width/2,                            origin.y + visibleSize.height - label->getContentSize().height));    // add the label as a child to this layer    this->addChild(label, 1);          return true;}void HelloWorld::menuCloseCallback(Ref* pSender){#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");    return;#endif    Director::getInstance()->end();#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)    exit(0);#endif}void HelloWorld::menuItem1Callback(cocos2d::Ref* pSender){hideAllSprite();sprite[0]->setVisible(true);}void HelloWorld::menuItem2Callback(cocos2d::Ref* pSender){hideAllSprite();sprite[1]->setVisible(true);}void HelloWorld::menuItem3Callback(cocos2d::Ref* pSender){hideAllSprite();sprite[2]->setVisible(true);}void HelloWorld::menuItem4Callback(cocos2d::Ref* pSender){hideAllSprite();sprite[3]->setVisible(true);}void HelloWorld::menuItem5Callback(cocos2d::Ref* pSender){hideAllSprite();sprite[4]->setVisible(true);}void HelloWorld::hideAllSprite(){for (auto p : sprite){if (p->isVisible())p->setVisible(false);}}
 

Executable program


Author: CCY

Contact: 810278677@qq.com


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.