重开发者的劳动成果,转载的时候请务必注明出处:http://blog.csdn.net/haomengzhu/article/details/30477587

为了方便游戏开发者,Cocos2d-x 内置了 3 种特殊的 Layer; 具体如下所示: LayerColor:一个单纯的实心色块。 LayerGradient:一个色块,但可以设置两种颜色的渐变效果。 Menu:十分常用的游戏菜单。
LayerColor 与 与 LayerGradient 这两个层十分简单,都仅仅包含一个色块。 不同的是,前者创建的是一个实×××块,而后者创建的是一个渐变色块; 来看一下具体的效果显示:



LayerColor拥有以下初始化方法: 如果采用指定了宽与高的初始化方法,则创建一个指定大小的色块; 如果采用不指定大小的初始化方法,则创建一个屏幕大小的色块。
LayerColor 的创建方法和初始化方法如下所示:

/** creates a fullscreen black layer */ static LayerColor* create(); /** creates a Layer with color, width and height in Points */ static LayerColor * create(const Color4B& color, GLfloat width, GLfloat height); /** creates a Layer with color. Width and height are the window size. */ static LayerColor * create(const Color4B& color); CC_CONSTRUCTOR_ACCESS: LayerColor(); virtual ~LayerColor(); bool init(); bool initWithColor(const Color4B& color, GLfloat width, GLfloat height); bool initWithColor(const Color4B& color);
LayerGradient 与 LayerColor 类似,但是它在初始化时需要指定两种颜色以及渐变的方向。 在初始化方法中,start参数为起始颜色,end 参数为结束颜色,而 v 是方向向量。 LayerGradient 的创建方法和初始化方法如下所示:

/** Creates a fullscreen black layer */ static LayerGradient* create(); /** Creates a full-screen Layer with a gradient between start and end. */ static LayerGradient* create(const Color4B& start, const Color4B& end); /** Creates a full-screen Layer with a gradient between start and end in the direction of v. */ static LayerGradient* create(const Color4B& start, const Color4B& end, const Point& v); CC_CONSTRUCTOR_ACCESS: LayerGradient(); virtual ~LayerGradient(); virtual bool init(); /** Initializes the Layer with a gradient between start and end. * @js init * @lua init */ bool initWithColor(const Color4B& start, const Color4B& end); /** Initializes the Layer with a gradient between start and end in the direction of v. * @js init * @lua init */ bool initWithColor(const Color4B& start, const Color4B& end, const Point& v);
在色块创建后,也可以通过下面列举的方法来修改色块大小:

/** change width in Points*/ void changeWidth(GLfloat w); /** change height in Points*/ void changeHeight(GLfloat h); /** change width and height in Points @since v0.8 */ void changeWidthAndHeight(GLfloat w ,GLfloat h);
Menu:游戏菜单 菜单是游戏不可或缺的一部分。 在 Cocos2d-x 中,菜单由两部分组成,分别是菜单项和菜单本身。 MenuItem 表示一个菜单项,每个菜单项都是一个独立的按钮,定义了菜单的视觉表现和响应动作; Menu 则是菜单,它负责将菜单项组织到一起并添加到场景中,转换屏幕的触摸事件到各个菜单项。
菜单项的创建通常需要规定普通状态、按下状态和被点击后的响应对象以及响应方法。 下面我们以一个图片菜单项为例介绍一下菜单项的创建,相关代码如下:

// Create a "close" menu item with close icon, it's an auto release object. MenuItemImage *pCloseItem = MenuItemImage::create( "CloseNormal.png",//普通状态下的图片 "CloseSelected.png",//按下状态下的图片 CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));//响应函数与对象 CC_BREAK_IF(! pCloseItem); 当点击按钮时回调到menuCloseCallback函数: 执行结束游戏逻辑:Director::getInstance()->end();
郝萌主友情提示: 多使用引擎提供的功能,会省不少时间与精力!