小桑博客

如果渡不过这不可渡的海,将成为这海中捞不起的沙

About Delegete

rootviewcontroller 上增加了一个tableviewcontroller,tablecell里有一个view,view里又有一个button

view大于2层就很难受了,delegate传来传去的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
view1:
  button - click
      -(void)click_event_callback;
  
tableviewcontroller
  view1.delegate = self;
  
  -(void)click_event_callback;
  
  
rootviewcontroller
  tableviewcontroller *tbvc.delegate = self;
  
  -(void)click_event_callback;
  

这样做的原因是点击button的时候,需要在rootviewcontroller.navagationcontroller中push一个viewcontroller,而tableviewcontroller是没有navagationcontroller的。

我们通常设置delegate

@property(nonatomic,assign,readwrite) id<*Protocol> _delegate;

用assign是防止产生交替dealloc死锁内存问题。

[Cocos2d-x wiki翻译]Transitions

转场动画 (Transitions)

介绍

One of the cool features that Cocos2d-x has to offer is the power of transitions within two different scene. Transitions are effects such as: wipe, fade, zoom, and split. You can use transitions to switch between Cocos2d-x Scene objects. Sceneclass is derived from CocosNode and it is similar to Layer. You can add other CocosNode, such as Layer(s) and Sprite(s) into a Scene.

Cocos2d-x提供的最爽的一个特性是在2个不同场景间转场的能力.转场的效果有:wipe, fade, zoom, 和 split. 你可以使用转场动画在Cocos2d-x场景对象中切换.Sceneclass继承自CocosNode,它和Layer非常相似.你可以增加其他CocosNode,如 Layer(s) 和 Sprite(s) 放到场景中.

Technically, a transition scene is an scene that performs a transition effect before setting control to the new scene.

技巧上说,转场的场景是一个在设置控制到新的场景前执行转场效果的场景.

创建转场动画

Time is the number of seconds for the transition. To apply transition to scenes, the syntax is as follows:

Time 是转场的秒数.为了把转场动画应用到场景中,语法如下:

1
CCDirector::sharedDirector()->replaceScene(CCTransitionFade::create(0.5,newScene));
Some transitions has custom parameter(s); for example, FadeTransition has the fade color as extra parameter. static CCTransitionFade* create(float duration,CCScene* scene, const ccColor3B& color); To enable a transition, it is not much more difficult. Here we have an small example:

一些转场可以有自定义参数;例如,FadeTransition有fade color作为额外参数.

1
static CCTransitionFade* create(float duration,CCScene* scene, const ccColor3B& color);

运行转场动画其实一点不难,这儿有一个小例子:

1
2
3
4
5
CCScene *s = SecondPage::scene();

CCDirector::sharedDirector()->setDepthTest(true);

CCTransitionScene *transition = CCTransitionPageTurn::create(3.0f, s, false);
If you run this you will have a “page turn” effect. This is, like turning the page on a paper made book.

如果运行这段代码,你会看到翻页效果.看起来就像是一页一页翻书。

更多转场动画

There are many more transition types, you can see the full list in the class reference, in the official Cocos2D-X documentation.

想知道更多转场动画类型,你可以在官方Cocos2D-X文档的相关类中参考完整列表。

Last updated by Zhe Wang at Updated about 1 month ago.

Comment

[Cocos2d-x wiki翻译]Particles

粒子(Particles)

简介

The term particle system refers to a computer graphics technique that uses a large number of very small sprites or other graphic objects to simulate certain kinds of “fuzzy” phenomena, which are otherwise very hard to reproduce with conventional rendering techniques - usually highly chaotic systems, natural phenomena, and/or processes caused by chemical reactions.

术语粒子系统关系到计算机图形学技术,使用大量非常小的sprite或其他图像对象来模拟特定种类的”模糊”现象,通过常规的渲染技术是很难制造的——一般来说有混乱系统、自然现象、或者活学反应引起的过程。

Point vs Quad

In early versions of Cocos2d-x, there were two types of particle system in cocos2d-x: Quad and Point particle system:

在Cocos2d-x早期版本中,Cocos2d-x里粒子系统有两种类型:Quad 和 Point粒子系统:

  • CCParticleSystemQuad
  • CCParticleSystemPoint
The CCParticleSystemQuad has these additional features that CCParticleSystemPoint doesn’t support:

CCParticleSystemQuad有很多特性是CCParticleSystemPoint不支持的:

- Spinning particles: particles can rotate around its axis. CCParticleSystemPoint ignores this property. - Particles can have any size. In CCParticleSystemPoint if the size is bigger than 64, it will be treated as 64. - The whole system can be scaled using the scale property.
  • Spinning particles:粒子可以绕自身的轴旋转。CCParticleSystemPoint忽略了该属性。
  • 粒子可以为任意大小。在CCParticleSystemPoint中,如果大小大于64时,就视为64。
  • 通过scale属性可以缩放整个系统。
Because of CCParticleSystemPoint does not support CCParticleBatchNode. As the result, CCParticleSystemPoint has been removed from cocos2d-x particle system.

由于CCParticleSystemPoint不支持CCParticleBatchNode.所以,CCParticleSystemPoint已经从cocos2d-x粒子系统里移除了.

CCParticleBatchNode

A CCParticleBatchNode can reference one and only one texture (one image file, one texture atlas). Only the CCParticleSystems that are contained in that texture can be added to the CCSpriteBatchNode. All CCParticleSystems added to a CCSpriteBatchNode are drawn in one OpenGL ES draw call. If the CCParticleSystems are not added to a CCParticleBatchNode then an OpenGL ES draw call will be needed for each one, which is less efficient.

CCParticleBatchNode可以引用且只可以引用1个texture(一个图片文件,一个texture图集).只有CCParticleSystem可以增加到CCSpriteBatchNode中. 所有增加到CCSpriteBatchNode中的CCParticleSystem是在OpenGL ES调用绘图函数时绘制的. 如果CCParticleSystem没有增加到CCParticleBatchNode中,OpenGL ES会调用每个粒子系统的绘图函数,这样做是低效的.

创建Quad粒子系统

1
2
CCParticleSystemQuad* m_emitter = newCCParticleSystemQuad();
m_emitter = CCParticleFire::create();

重力和半径模式

重力模式 Gravity Mode

Gravity Mode lets particles fly toward or away from a center point. Its strength is that it allows very dynamic, organic effects. You can set gravity mode with this line:

重力模式让粒子围绕一个中心点移近或移远.它的优点是非常动态,有组织有规则的效果.你可以通过下面这行代码设置重力模式:

1
2
3
4
5
// Gravity Mode
this->m_nEmitterMode = kCCParticleModeGravity;

// Gravity Mode: gravity
this->modeA.gravity = ccp(0,-90);
These properties are only valid in Gravity Mode:

下面这些属性只在重力模式下支持:

- gravity (a CGPoint). The gravity of the particle system - speed (a float). The speed at which the particles are emitted - speedVar (a float). The speed variance. - tangencialAccel (a float). The tangential acceleration of the particles. - tangencialAccelVar (a float). The tangential acceleration variance. - radialAccel (a float). The radial acceleration of the particles. - radialAccelVar (a float). The radial acceleration variance.
  • 重力(CGPoint)。粒子系统的重力。
  • 速度(float)。粒子发射时的速度。
  • 速度变量speedVar(float)。速度的变异数。
  • tangencialAccel(float)。粒子的正切加速度。
  • tangencialAccelVar(float)。粒子正切加速度的差异数。
  • radialAccel(float)。粒子的径向加速度。
  • radialAccelVar(float)。粒子径向加速度的差异数。

半径模式 Radius Mode

Radius Mode causes particles to rotate in a circle. It also allows you to create spiral effects with particles either rushing inward or orating outward. You set radius mode with this line:

半径模式会使粒子以圆圈方式旋转.它也可以创造螺旋效果让粒子急速前进或后退.你可以通过下面这行代码设置半径模式:

1
2
3
4
5
6
// Radius Mode
this->m_nEmitterMode = kCCParticleModeRadius;

// Radius Mode: startRadius
this->modeB.startRadius = 0;
this->modeB.startRadiusVar = 0;//ccp(0,0);
These properties are only valid in Radius Mode:

下面这些属性只在半径模式下支持:

- startRadius (a float). The starting radius of the particles - startRadiusVar (a float). The starting radius variance - endRadius (a float). The ending radius of the particles. - endRadiusVar (a float). The ending radius variance - rotatePerSecond (a float). Number of degress to rotate a particle around the source pos per second. - rotatePerSecondVar (a float). Number of degrees variance.
  • startRadius(float)。粒子开始时的半径。
  • startRadiusVar(float)。粒子开始时的半径变异数。
  • endRadius(float)。粒子结束时的半径。
  • endRadiusVar(float)。结束时粒子的半径变异数。
  • rotatePerSecond(float)。粒子围绕原点每秒旋转的度数。
  • rotatePerSecondVar(float)。度数的变异数。

各模式下的通用属性

粒子通用属性:

- startSize: Start size of the particles in pixels - startSizeVar - endSize: Use kCCParticleStartSizeEqualToEndSize if you want that the start size == end size. - endSizeVar - startColor (a ccColor4F) - startColorVar (a ccColor4F) - endColor (a ccColor4F) - endColorVar (a ccColor4F) - startSpin. Only used in CCParticleSystemQuad - startSpinVar. Only used in CCParticleSystemQuad - endSpin. Only used in CCParticleSystemQuad - endSpinVar. Only used in CCParticleSystemQuad - life: time to live of the particles in seconds - lifeVar: - angle: (a float). Starting degrees of the particle - angleVar - positon: (a CGPoint) - posVar - centerOfGravity (a CGPoint)
  • startSize: 开始时粒子的像素大小
  • startSizeVar
  • endSize: 如果你愿意的话使用kCCParticleStartSizeEqualToEndSize,这样开始大小 == 结束大小
  • endSizeVar
  • startColor开始颜色 (ccColor4F)
  • startColorVar (ccColor4F)
  • endColor结束颜色 (ccColor4F)
  • startSpin开始的旋转角度。只用于CCParticleSystemQuad
  • startSpinVar.只用于CCParticleSystemQuad
  • endSpin结束时的旋转角度。只用于CCParticleSystemQuad
  • endSpinVar。只用于CCParticleSystemQuad
  • life:粒子存活的时间,单位秒
  • lifeVar:
  • angle:(float)。粒子发射时的角度
  • angleVar
  • positon:(CGPoint)
  • posVar
  • centerOfGravity(CGPoint)重力中心点

粒子系统通用属性:

- emissionRate (a float). How many particle are emitted per second - duration (a float). How many seconds does the particle system (different than the life property) lives. Use kCCParticleDurationInfinity for infity. - blendFunc (a ccBlendFunc). The OpenGL blending function used for the system - positionType (a tCCPositionType). Use kCCPositionTypeFree (default one) for moving particles freely. Or use kCCPositionTypeGrouped to move them in a group. - texture (a CCTexture2D). The texture used for the particles
  • emissionRate (float)。每秒发射多少粒子。
  • duration (float)。粒子系统可以存活多少秒(与life属性不同)。使用kCCParticleDurationInfinity为无限时间。
  • blendFunc (ccBlendFunc)。系统中使用的OpenGL混合方法。
  • positionType (CCPositionType)。粒子自由移动使用kCCPositionTypeFree(默认)。或者使用kCCPositionTypeGrouped,使粒子在集合中移动。
  • texture纹理(CCTexture2D)。粒子使用的纹理。

示例

cocos2d-x comes with some predefined particles that can be customized in runtime. List of predefined particles:

cocos2d-x里内置的预制粒子是可以在运行时自定义的.内置粒子列表:

  • CCParticleFire: Point particle system. 使用重力模式.
  • CCParticleFireworks: Point particle system. 使用重力模式.
  • CCParticleSun: Point particle system. 使用重力模式.
  • CCParticleGalaxy: Point particle system. 使用重力模式.
  • CCParticleFlower: Point particle system. 使用重力模式.
  • CCParticleMeteor: Point particle system. 使用重力模式.
  • CCParticleSpiral: Point particle system. 使用重力模式.
  • CCParticleExplosion: Point particle system. 使用重力模式.
  • CCParticleSmoke: Point particle system. 使用重力模式.
  • CCParticleSnow: Point particle system. 使用重力模式.
  • CCParticleRain: Point particle system. 使用重力模式.

参考

粒子 cocos2d中的粒子系统

[Cocos2d-x wiki翻译]Effects

Effects

介绍

Effects are a special kind of action. Instead of modifying normal properties like opacity, position, rotation, or scale, they modify a new kind of property: the grid property.

Effect是特殊类型的动作.与修改常规的属性如透明度、位置、旋转或缩放等不同,它们修改的是一种新类型的属性:grid属性.

A grid property is like a matrix, it is a network of lines that cross each other to form a series of squares or rectangles.

grid属性像是一个矩阵,是由相互交叉形成一系列正方形和矩形的线组成的网络。

These special actions render any CocosNode object (Layer, Scene, Sprite, etc.) into the grid, and you can transform the grid by moving its vertices.

这些特殊的动作可以渲染任一CocosNode对象 (Layer, Scene, Sprite, 等.)到grid中,你可以通过顶点来变换grid.

There are 2 kind of grids: tiled grids and non-tiled grids. The difference is that the tiled grid is composed of individual tiles while the non-tiled grid is composed of vertices.

一共有2类grid: 瓦片grid(tiled grids)和非瓦片grid(non-tiled grids).它们的区别在于瓦片grid是由独立的瓦片(tile)组成,而非瓦片grid由顶点组成。

The following is an example of Ripple3D action, who uses a Grid3D (non-tiled) grid:

下面是Ripple3D动作例子,它使用的是 Grid3D (非瓦片的) grid:

and the following is an example of FadeOutTR action, who uses a TiledGrid3D (tiled) grid:

接下来是FadeOutTR动作例子,它用的是TiledGrid3D (瓦片) grid:

用法

Like any other action, it is executed by the runAction. eg:

和其他动作一样,是通过runAction执行的.例如:

1
2
3
// Create an sprite
CCSprite* grossini = CCSprite::create("grossini.png");
grossini->runAction(CCLiquid::create(4, 20, ccg(10,10), 5));
Liquid, like any other grid action, receives the grid parameter. You can adjust the quality of the effect by increasing the size of the grid. But it also implies less FPS. The Effects are IntervalAction actions so you can treat them like any other action. eg:

和其他grid动作一样,Liquid会接收一个grid参数.你可以通过增加grid的大小来调整effect(效果)的品质.但是它也意味着有很少的FPS.
Effect是IntervalAction动作(延时动作),所以你可以用像其他动作的处理方式一样来处理它们.例如:

1
2
3
4
5
6
7
8
// create a Lens3D action
CCActionInterval* lens = CCLens3D::create(ccp(240,160),240,ccg(15,10),8);

// create a Waved3D action
CCActionInterval* waves = CCWaves3D::create(18,80,ccg(15,10),10);

// create a sequence an repeat it forever
grossini->runAction(CCRepeatForever::create((CCSequence*)CCSequence::create(waves, lens, NULL ) ) );
The following is the list of the available Grid3D (non-tiled) actions in v2.1.0:

下面是v2.1.0版本中Grid3D(non-tiled) actions的可用列表:

Shaky3D Waves3D FlipX3D FlipY3D
Lens3D Liquid Waves Twirl
Ripple3D
|
The following is the list of the available TiledGrid3D (tiled) actions

下面是TiledGrid3D(tiled) 动作可用的列表:

ShakyTiles3D ShatteredTiles3D ShuffleTiles FadeOutTRTiles
FadeOutBLTiles FadeOutUpTiles FadeOutDownTiles TurnOffTiles
WavesTiles3D JumpTiles3D SplitRows SplitCols

参考

cocos2d-iphone cocos2d’s effects简介

[Cocos2d-x Wiki翻译]骨骼动画

骨骼动画 vs. 精灵表

You can creat animations using “sprite sheets” which is quick and easy. Until you realize your game needs lots of animations and the memory consumption goes way up, together with the time required to load all the data. Also, to limit the size, you need to limit yourself to a low FPS for the animation, which also means the animation doesn’t look as smooth as you’d like. This is where skeletal animation comes in.

创建动画又快又简单的方法是使用“精灵表”.当你意识到游戏需要大量动画,内存消耗会涨上来,而且需要耗时去加载所有数据.此外,限于大小,你需要为了动画限制自己使用低FPS,这意味着动画不是你想要的那么平滑.这就是骨骼动画的由来.

骨骼动画简述

Skeletal animation is a technique in cocos2d-x animation in which a character is represented in two parts: a surface representation used to draw the character (called skin or mesh) and a hierarchical set of interconnected bones (called the skeleton or rig) used to animate (pose and keyframe) the mesh.

骨骼动画是cocos2d-x动画在人物渲染方面的技术,分二个部分:用于绘制人物的外观呈现(被称为蒙皮或者mesh)和用于mesh进行动画(造型和关键帧) 的一组分层的相互连接的骨骼.

Cocos2d-x provides a way to have 2d skeletal animations in your applications. The process of skeletal animation may be a bit complicated to setup, but using them afterwards is easy, and there are some tools to simplify the process.

在你的应用中,Cocos2d-x提供了拥有2d骨骼动画的方式.构建骨骼动画过程开始可能有点复杂,但随后用起来却非常简单,而且有一些工具可以简化此过程.

When using skeletal animation, the animation is composed of several bones which are connected to one another. Affecting a bone also affects all of its children. By composing different transformations on each bone, you obtain different poses for the skeleton.

当使用骨骼动画时,动画由一些相互连接的骨骼组成。影响一个骨骼将会影响其所有的子对象。通过每根骨头上不同的变换组合,你会得到骨骼的各种造型。

Now, if you define keyframes with certain transformations for a point in time for each of the bones in the skeleton, you can interpolate between the keyframes to obtain a smooth transition and thus animate the skeleton.

现在,如果你定义了关键帧,即某个时间点骨骼中每根骨头特定的变换,你就能在关键帧之间插入平滑的过渡,从而使骨骼运动。

In the attached code, I used a class named Transformation, which contains data about 2D transformations, like translation, rotation and scale. Then, a Keyframe is defined by a frame number and one such Transformation. A collection of Keyframes defines a KeyframeAnimation. Finally, a SkeletonAnimation is a collection of KeyframeAnimations, one for each bone in the skeleton.

在附加的代码中,我使用一个名叫Transformation的类,它含有2D变换的数据,如translation(平移)、rotation(旋转)和scale(缩放)。通过帧的编号和一个Transformation能定义一个关键帧。关键帧的集合定义了一个KeyFrameAnimation.最后,骨骼动画就是一个KeyFrameAnimation的集合,每个KeyFrameAnimation应用于骨骼中的每根骨头。

Separately, you use a Skeleton, which keeps a list of Joints that define the hierarchy of bones in the skeleton. Different from “sprite sheets”,each bone is then assigned a certain texture, like the ones below:

另外,你使用骨骼,它保存了关节列表,关节定义了骨骼中骨头的层级。不同于“精灵表”,每根骨头指定了特定的texture,如下所示:

骨骼动画工具

So far as we know, [CocosBuilder](http://cocosbuilder.com/) is a great, free (MIT license) tool for creating skeleton animations. CocosBuilder is built for Cocos2d’s Javascript bindings, which means that your code, animations, and interfaces will run unmodified in Cocos2d-x. A tutorial for cocos2d-iphone can be found at the [Zynga Engineering blog](http://code.zynga.com/2012/10/creating-a-game-with-cocosbuilder/)

据我们所知,在创建骨骼动画方面CocosBuilder是一个不错的、免费(MIT协议)的工具。
CocosBuilder为Cocos2d的Javascript绑定而创建的。这意味着你的代码、动画和接口会无修改地在Cocos2d-x中运行。
cocos2d-iphone的教程可以在Zynga Engineering blog找到。

与cocosbuilder动画协作

You can use CocosBuilder for creating character animations, animating complete scenes or just about any animation you can imagine. The animation editor has full support for multiple resolutions, easing between keyframes, boned animations and multiple timelines to name a few of the features. h3.The Basics In the bottom of the main window you can find the timeline. You use the timeline to create your animations.

你可以使用CocosBuilder创建人物动画,全场景动画或者你所想的任何动画。该动画编辑器已完全支持多分辨率、关键帧间的缓冲动画、骨骼动画和多时间轴等特性。

基础

在主窗口的下部,你可以找到时间轴。你可以使用时间轴来创建你的动画。

By default your ccb-file has a single timeline that is 10 seconds long. CocosBuilder edits animations at a frame rate of 30 frames per second, but when you play back the animation in your app it will use whatever you have set cocos2d to use (the default in cocos2d is 60 fps). The current time is displayed in the top right corner, and has the format minute:second:frame. The blue vertical line also shows the current time. Click the time display to change the duration of the current timeline.

默认情况下你的ccb-file只有一条时长10秒的时间轴。CocosBuilder编辑动画的帧率是每秒30帧,但是当你在应用程序中回放动画时,会使用你给cocos2d设置的帧率(cocos2d中默认是60fps)。当前时间会在右上角显示,格式是分:秒:帧。蓝色垂直线也显示了当前时间。单击显示时间以更改当前时间线的时间间隔。

增加 Keyframes

Animations in CocosBuilder are keyframe based. You can add keyframes to different properties of a node and CocosBuilder will automatically interpolate between the keyframes, optionally with different types of easing. To add a keyframe, first expand the view of the node by clicking the triangle to the right of the name of the node. This will reveal all the animatable properties of the node. What can be animated varies slightly depending on what type of node you have selected. Once the properties are visible you can click the property in the timeline with the option key held down. This will create a new keyframe at the time of the click. Alternatively, you can create a new keyframe at the time of the time marker by selecting a node then choosing Insert Keyframe in the Animation menu. Keyframes are automatically added at the current time if you transform a node in the canvas area, given that the transformed property already has one or more keyframes in the timeline.

CocosBuilder中的动画是基于关键帧的。你可以添加关键帧以设置node的不同属性并且CocosBuilder会自动在关键帧间插入不同类型的可选(ease)缓冲动作。

为了添加关键帧,首先通过点击node名字右边的三角形展开node的视图。上面会展现该node所有可动画的属性。基于你选择的node类型,可以动画的属性会稍微有点不一样。凡是可见的属性,你可以在时间轴中按住option键并点击该属性。在点击的那个时间点就会创建新的关键帧。或者,你可以通过选择一个node再在Animation菜单中选Insert Keyframe从而在时间标志器的那个时间点生成一个新的关键帧。

如果你在画布区域变换一个node,并且该node所变换的属性在时间轴上已经有一个或多个关键帧,那么CocosBuilder会自动在当前时间点添加关键帧。

编辑 Keyframes

You edit a specific keyframe of a node by moving the time marker to the time of the keyframe and selecting the node. You can focus on a keyframe by double clicking it (which will select the node and move the time marker).

移动时间标志器至特定关键帧的时间点并选择该node,编辑该关键帧。你可以通过双击关键帧聚焦于该帧(聚焦即选择该node并移动时间标志器)。

You can select keyframes and move them together by dragging a selection box around them. You can also copy and paste keyframes between nodes. Make sure you only have one selected node when pasting the keyframes. The keyframes will be pasted starting at the time of the time marker.

你可以选择关键帧并通过拖拉它们周围的选择框来移动它们。你也可以在node间复制、黏贴关键帧。当黏贴关键帧时,确保你只选择了一个node。关键帧会黏贴在时间标志线标志的时间。

If you have selected a set of keyframes it is possible to reverse the order of them by selecting Reverse Selected Keyframes in the Animation menu. Use the Stretch Selected Keyframes… option to speed up or slow down an animation by a scaling factor.

如果你已经选择了一系列关键帧,可以通过选择Animation菜单中的Reverse Selected Keyframes来反向关键帧的次序。使用Stretch Selected Keyframes选项可以通过一个缩放因子来加速或者减速动画。

导入多张连续图片

If you have an animation created by sprite frames it can be tedious to move each individual frame to the timeline. CocosBuilder simplifies this process by automatically importing a sequence of images. Select the frames that you want to import in the left hand project view, then select a CCSprite in the timeline. Now choose Create Frames from Selected Resources in the Animation menu. The frames will automatically be created at the start of the marker. If you need to slow down the animation, select the newly created keyframes and use the Stretch Selected Keyframes… command.

如果你通过sprite frame帧组创建动画,需要冗长的时间来将每个独立的帧移至时间轴上。CocosBuilder通过自动导入图像序列简化了这一过程。选择你想要导入到左边项目视图的帧,然后选择时间轴上的一个CCSprite。现在选择Animation菜单中的Create Frames from Selected Resources.这些帧会在时间标志线开始的地方添加。如果你需要放慢动画,选择新创建的关键帧组,并使用Stretch Selected Keyframes…命令。

应用渐变

CocosBuilder offers a carefully selected subset of the easings provided by cocos2d. To apply an easing right click between two keyframes and select the type of easing that you want to apply.

CocosBuilder提供了cocos2d给予的一些精心挑选的缓冲动作(easing)子集。应用一个缓冲动作只需在两个关键帧之间右键点击并选择你想应用的缓冲动作的类型即可。

Some of the easings have additional options, after the easing has been applied you can right click again and select Easing Setting… from the popup menu.

一些缓冲动作有额外的选项,在应用缓冲动作之后,你可以再次右击并从弹出菜单中选择Easing Setting…。

使用多个时间轴

A very powerful feature of CocosBuilder’s animation editor is the ability to have multiple timelines in a single file. You can name the different sequences and play them back from your code by using their name. It’s even possible to smoothly transition between the different timelines. To select, add or edit your timelines use the timeline popup menu:

CocosBuilder的动画编辑器有一个非常强大的特性就是在单个文件中可以含有多个时间轴。你可以命名不同的序列并通过它们的名字从代码中播放它们。在不同的时间轴之间会有平滑的过渡。

在选择之前,使用时间轴弹出菜单添加并编辑你的时间轴:

In the edit timelines dialog you can get an overview of your timelines, rename them, add new ones and (optionally) set one of the timelines to automatically start playback directly when the ccbi-file is loaded by your app.

在编辑时间轴的对话框中,你可以获得时间轴的大致信息、重命名它们、添加新的时间轴以及(可选)设置时间轴中的一条在ccbi文件从你的应用程序加载后立即自动开始播放。

Properties in timelines that do not have keyframes set share their values across timelines. E.g. if you move one node in one timeline it will be moved in all timelines as long as they do not have a keyframe set for the position property. I can sometimes be useful to add a single keyframe to a property just to override the shared value for a specific timeline.

没有设置关键帧的时间轴中的属性会在时间轴时间共享它们的值。例如,如果你移动某条的一个node,只要它没有为位置属性设置关键帧,它就会在所有的时间轴中被移动。有时,我觉得为一个特定的时间轴添加单个关键帧来覆盖共享值是挺有用的。

锁定时间轴

You can automatically play back a sequence of timelines by chaining them. You can also use this feature for automatically looping a timeline.

你可以通过锁定时间轴来自动回放时间轴序列。你也可以使用这个特性来自动重播一个时间轴。

To have a timeline play in sequence, click the No chained timeline text and select the timeline you want to play right after the current one.

为了播放时间轴序列中的一个时间轴,点击No chained timeline文本并选择当前时间轴后你想播放的那个。

通过代码播放动画

To programmatically control the animations you create with CocosBuilder you will need to retrieve theCCBAnimationManager. The animation manager will be assigned to the nodes userObject when the ccbi-file is loaded.

想要通过代码控制你用CocosBuilder创建的动画,你需要检索CCBAnimationManager。当ccbi文件加载时,该动画管理器将分配node userObject。

1
CCNode *myNodeGraph = ccbReader->readNodeGraphFromFile("myFile.ccbi", this);
The action manager will be returned as an autoreleased object. To play back a specific timeline call therunAnimationsForSequenceNamed: method. If a timeline is currently playing it will be immediately stopped when calling this method.

动作管理器会作为一个自动释放对象返回。回放特定的时间轴需调用runAnimationsForSequenceNamed: 方法。如果时间轴当前正在播放,当调用此方法时它会立刻停止。

1
animationManager->runAnimationsForSequenceNamed("My Timeline");
Optionally, you can use a tween duration to smoothly transition to the new timeline. Where possible linear interpolations will be used for the transition.

或者,你可以使用时间轴之间的时间间隔来平滑过渡到新的时间轴。一般情况下线性插入会应用于此过渡。

1
animationManager->runAnimationsForSequenceNamedTweenDuration("My Timeline",0.5f);
It is also possible to receive a callback whenever a timeline has finished playing. You will receive these callbacks even if another timeline is chained in sequence. Use the CCBAnimationManagerDelegate to receive the callbacks.

也可以在时间轴播放完毕后接收一个回调。即使另外的时间轴锁在序列中,你也能接收到这些回调。你可以用CCBAnimationManagerDelegate来接收回调。

总结

Thank you taking the time to read through the tutorial and happy coding!If you have other tools for skeleton animation,please let us known or post to this wiki.

谢谢你们花时间来阅读本教程,祝编程愉快!如果你有其他骨骼动画的动作,请通知我们或者发邮件到此wiki。

参考

Creating a game with cocosbuilder
CocosBuilder Documentation

[Cocos2d-x wiki翻译]Scheduler and Timer Callback

Scheduler and Timer Callback

Scheduler is responsible for triggering the scheduled callbacks.

调度器负责触发调度回调.

两种不同类型的回调 (selectors):

update selector: the ‘update’ selector will be called every frame. You can customize the priority. custom selector: A custom selector will be called every frame, or with a custom interval of time. The ‘custom selectors’ should be avoided when possible. It is faster, and consumes less memory to use the ‘update selector’.
  • 更新selector: ‘update’ selector会被每个frame调用.你可以自定义优先级.
  • 自定义selector: 自定义selector会被每个frame调用, 或自定义的时间段内调用.

‘custom selectors’尽可能避免使用。相对于使用’update selector’来说,它比较快,且内存消耗较小.

CCScheduler vs. NSTimer

The Cocos2D Scheduler provides your game with timed events and calls. You should not use NSTimer. Instead use CCScheduler class. The reasons as follow:

Cocos2D Scheduler 为你的游戏提供了时间事件和调用.你最好不要使用NSTimer,而用CCScheduler类替代.

原因如下:

CCNode objects know how to schedule and unschedule events,and using the Cocos2D Scheduler has several distinct advantages over just using NSTimer.
- CCNode objects know how to schedule and unschedule events,and using the Cocos2D Scheduler has several distinct advantages over just using NSTimer. - The scheduler calls get deactivated whenever the CCNode is no longer visible or is removed from the scene. - The scheduler calls are also deactivated when Cocos2D is paused and are rescheduled when Cocos2D is resumed. - The scheduler delivers a interval time of the milliseconds that have passed since the last call.This interval time is useful in Physics engines. - Using scheduler with this->scheduleUpdate(); call ensures that your update function will be called before each frame needs to be rendered.
  • CCNode对象知道如何去调度和解除调度事件,和仅使用NSTimer相比,使用Cocos2D Scheduler有很多独特的优点.
  • 每当CCNode不再可见或者需从场景中移除时,调度器调用会失效。
  • 当Cocos2D暂停或者Cocos2D继续时重新调度,调度器调用也会失效。
  • 调度器会传递距离上一次调用的间隔时间(单位毫秒)。间隔时间在物理引擎中十分有用。
  • 通过调用this->scheduleUpdate();使用调度器能确保你的更新方法在每帧需要渲染前调用。
Accordingly,CCScheduler can save you a lot of time over NSTimer and let you focus on the mechanics of your game. Last updated by Iven Yang at Updated about 1 month ago.

因此,CCScheduler会比NSTimer节省很多时间,让你更加关注于你的游戏构成.

Comment

[Cocos2d-x wiki翻译]Animations

动画(Animations)

Animations Manual Animation Sprite Sheet Animation Creating from .png and .plist file File animation Skeleton Animation Comment

Frame Animation(帧动画)

You can create an animation from a series of image file, like this:

你可以通过多张图片文件来创建一个动画,比如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 CCAnimation *animation = CCAnimation::create();
 
 // load image file from local file system to CCSpriteFrame, then add into CCAnimation
 for (int i = 1; i < 15; i++)
 {
     char szImageFileName[128] = {0};
     sprintf(szImageFileName, "Images/grossini_dance_%02d.png", i);
     animation->addSpriteFrameWithFileName(szImageFileName);  
 }

animation->setDelayPerUnit(2.8f / 14.0f); // This animation contains 14 frames, will continuous 2.8 seconds.
animation->setRestoreOriginalFrame(true); // Return to the 1st frame after the 14th frame is played. 

CCAnimate *action = CCAnimate::create(animation);
sprite->runAction(action);  // run action on sprite object
Note that CCAnimation is composed by sprite frames, delay time per frame, durations etc, it’s a pack of “data”. While CCAnimate is an action, which is created base on CCAnimation object.

注意CCAnimation是由sprite frame帧组、单个frame延时,持续时间等组成的,它是一组”数据”. 而CCAnimate是一个action,它是基于CCAnimation对象创建的。

Sprite Sheet Animation

Although manual animation is very easy to understand, it’s rarely used in real game projects. Instead, sprite sheet animation is the common solution of 2D animations.

尽管帧动画是非常易于理解的,但事实上,它在真实游戏项目中是非常少用到的.相反,sprite sheet animation是2D动画中最常见的解决方案.

This is a typical sprite sheet. It can be a sequence of sprite frames for an animation, or can be images pack that will be used in a same scene.

下面是一个典型的sprite sheet.它是动画中的一连串sprite frames,或者是可以在一个场景中用到的一组图片.

In OpenGL ES 1.1 period, sprite sheets was widely used for these benefits: Reduce times of file I/O. Loading a big sprite sheet file is faster than loading lots of small files. Reduce the memory consumption. OpenGL ES 1.1 can only use power-of-two sized textures (that is a width or height of 2,4,864,128,256,512,1024,…). In other words, OpenGL ES 1.1 allocates power-of-two sized memory for each texture even if this texture has smaller width and height. So using packed sprite sheet image will reduce the fragments of memory. Reduce the draw calls to OpenGL ES draw method and speed up rendering.

在OpenGL ES 1.1时代,sprite sheets被广泛使用是得益于:

  1. 减少文件I/O时间.加载一个大的sprite sheet文件比加载多个小文件要快得多.
  2. 减少内存消耗.OpenGL ES 1.1仅可用2幂次方大小的texture(通常为 2,4,864,128,256,512,1024,…的宽高).换言之,如果宽高比较小的话,OpenGL ES 1.1甚至为每个texture分配2幂次方大小内存.所以使用成组的 sprite sheet图片会减少内存碎片.
  3. 减少 OpenGL ES 调用方法绘制,加速渲染.
Cocos2d-x v2.0 upgraded to OpenGL ES 2.0 based. OpenGL ES 2.0 doesn’t allocate power-of-two memory block for textures anymore, but the benefit of reducing file I/O times and draw calls are still working.

Cocos2d-x v2.0已更新,是基于OpenGL ES 2.0的.OpenGL ES 2.0不再为textures分配2的幂次方内存块,但减少文件系统I/O和绘图调用时间的好处仍然是有效的.

Then how about the animation? As we can see, sprite sheet has no MUST-BE relationship with animations. But considering to these benefits above, sprite sheet animations are efficient. There’re different ways to create sprite sheet animations in cocos2d.

那该如何动画呢?正如我们看到的,sprite sheet与动画没有的必然关系.但考虑到上面这些益处,sprite sheet是有效的.在cocos2d中有很多种不同的方法来创建sprite sheet.

Creating from .png and .plist file

In cocos2d-x 0.x and 1.x versions, CCSpriteSheet works for this purpose. While CCSpriteBatchNode is a replacement of CCSpriteSheet since v2.0

在cocos2d-x 0.x和1.x版本中,CCSpriteSheet便是为此目的而生的.而CCSpriteBatchNode在v2.0版本之后替换了CCSpriteSheet

A CCSpriteBatchNode object contains the actual image texture of all the sprite frames. You must add it to a scene, even though it won’t draw anything itself; it just needs to be there so that it is part of the rendering pipeline. For example:

CCSpriteBatchNode对象包含了所有sprite frames中用到的真实图片texture.你必须在场景中添加它,甚至它自身什么都不用画;它只需要放到那里,这样它就成了rendering pipeline的组成部分.比如:

1CCSpriteBatchNode* spritebatch = CCSpriteBatchNode::create(“animations/grossini.png”); Next, you need to use the CCSpriteFrameCache singleton to keep track how frame names correspond to frame bounds – that is, what rectangular area of the sprite sheet. Example:
1
CCSpriteBatchNode* spritebatch = CCSpriteBatchNode::create("animations/grossini.png");

接下来,你需要使用CCSpriteFrameCache单例对象来保存frame名字如何对应到frame bounds—— 也就是,sprite sheet中的矩形区域.例如:

1
2
CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
cache->addSpriteFramesWithFile("animations/grossini.plist");
Once your sprite sheet and frames are loaded, and the sprite sheet has been added to the scene, you can create sprites that use these frames by using the “createWithSpriteFrameName” method, and adding it as a child of the sprite sheet:

一旦你的sprite sheet和frames已经加载完毕,并且sprite sheet已经增加到场景中了,你可以通过这些frame创建sprite,使用 “createWithSpriteFrameName” 方法,把它添加为sprite sheet的子对象:

1
2
3
m_pSprite1 = CCSprite::createWithSpriteFrameName("grossini_dance_01.png");
spritebatch->addChild(m_pSprite1);
addChild(spritebatch);
createWithSpriteFrameName method will find the corresponding coordinates and rectangle from grossini.plist, then “clip” the texture grossini.png to a sprite frame.

createWithSpriteFrameName方法会查找相应坐标和grossini.plist中定义的矩形,接着”裁剪”texture grossini.png到sprite frame.

Now we need to create a CCArray object and add all frames of the animation to it. In the case of this animation, we know all 14 frames have the same size, so we can use a nested loop to iterate through them all, and break the loop when we finish adding the 14th frame.

现在,我们需要创建CCArray对象,增加动画中的所有frame到此对象中。在这个动画例子中,我们知道这14个frame都有一模一样的尺寸,所以我们使用了嵌套循环来迭代,当我们完成增加第14个frame的时候中断循环.

1
2
3
4
5
6
7
8
9
10
CCArray* animFrames = CCArray::createWithCapacity(15);

char str[100] = {0};

for(int i = 1; i < 15; i++)
{
    sprintf(str, "grossini_dance_%02d.png", i);
    CCSpriteFrame* frame = cache->spriteFrameByName( str );
    animFrames->addObject(frame);
}
Finally, we need to create a CCAnimate action instance which we can run on the CCSprite. Below, we also wrap the CCAnimate action in a CCRepeatForever action that does what you would expect: repeats the animation forever,like so:

最后,我们需要创建CCAnimate动作实例,该实例能在CCSprite对像上运作.下面,我们还将CCAnimate动作封装到CCRepeatForever动作中,此动作正是你所需要的:重复动画,像这样:

1
2
CCAnimation* animation = CCAnimation::createWithSpriteFrames(animFrames, 0.3f);
m_pSprite1->runAction( CCRepeatForever::create( CCAnimate::create(animation) ) );

File animation

CCAnimationCache can load a xml/plist file which well describes the batch node, sprite frame names and their rectangles. The interfaces are much easier to use.

CCAnimationCache 可以加载xml/plist文件,此文件可以非常好的描述批量node,sprite frame names和它们的矩形. 这个接口更简单易用.

1
2
3
4
5
CCAnimationCache *cache = CCAnimationCache::sharedAnimationCache(); // "caches" are always singletons in cocos2d
cache->addAnimationsWithFile("animations/animations-2.plist");
CCAnimation animation = cache->animationByName("dance_1");  // I apologize for this method name, it should be getAnimationByName(..) in future versions
CCAnimate animate = CCAnimate::create(animation);  // Don't confused between CCAnimation and CCAnimate :)
sprite->runAction(animate);
Easy to use, isn’t it?

简单易用吧?哈哈

骨骼动画(Skeleton Animation)

请参考 Skeletal Animation 页.

评论

[Cocos2d-x wiki翻译]Actions

Actions

Actions are like orders given to any CCNode object. These actions usually modify some of the object’s attributes like position, rotation, scale, etc. If these attributes are modified during a period of time, they are CCIntervalAction actions, otherwise they are CCInstantAction actions. For example, the CCMoveBy action modifies the position property during a period of time, hence, it is a subclass of CCIntervalAction.

动作(Actions)就像给CCNode对象的命令一样。这些动作通常会修改对象的一些属性,如位置,旋转,缩放等。如果这些属性在一段时间内被修改,它们是CCIntervalAction动作(延时动作),相反则是 CCInstantAction 动作(瞬间动作).

例如,CCMoveBy动作是在一段时间内修改了位置属性,因此,它是CCIntervalAction的子类.

You can run TestCpp -> Actions Test to see the actions’ visual effects. And cocos2d-x/samples/Cpp/TestCpp/Classes/ActionsTest, ActionsEaseTest are good sample codes for the usage.

你可以运行TestCpp -> Actions Test 来查看动作的可视化效果。cocos2d-x/samples/Cpp/TestCpp/Classes/ActionsTest, ActionsEaseTest中的用法是非常好的代码示例。

例如:

1
2
// Move a sprite 50 pixels to the right, and 10 pixels to the top over 2 seconds.
CCActionInterval*  actionBy = CCMoveBy::create(2, ccp(50,10));
The CCIntervalAction actions have some interesting properties: They can be accelerated using the time-altered actions

CCIntervalAction动作有一些有意思的属性:

使用变速动作可以对CCIntervalAction动作进行加速等,变速动作有:

  • CCEaseIn
  • CCEaseOut
  • CCEaseInOut
  • CCSpeed
Etc. (See the ActionsEaseTest.cpp example for more info)

(更多信息,详见ActionsEaseTest.cpp实例)

You can pause/resume all actions by using the CCActionManager:

你可以通过用CCActionManager来暂停和恢复所有动作:

1
2
3
4
5
6
// Pause actions
CCDirector *director = CCDirector::sharedDirector();
m_pPausedTargets = director->getActionManager()->pauseAllRunningActions();
// resume actions
CCDirector *director = CCDirector::sharedDirector();
director->getActionManager()->resumeTargets(m_pPausedTargets);

Basic Actions

Basic actions are the ones that modify basic properties like:

基本动作是指修改基本属性如:

位置(position)

缩放(scale)

旋转(rotation)

可见性(visible)

不透明度(opacity)

颜色(color)

例如:

1
2
3
4
5
6
CCSprite *sprite = CCSprite::create("Images/grossini.png");
sprite->setPosition(ccp(100, 100));
addChild(sprite);

CCMoveBy* act1 = CCMoveBy::create(0.5, ccp(100, 0));
sprite->runAction(CCRepeat::create(act1, 1));
The act1 will be a CCMoveBy action of duration 0.5, but with the position value of ccp(100,0).

act1是持续0.5秒的CCMoveBy动作,并且使用ccp(100,0)作为移动的位置值.

评论

[Cocos2d-x wiki翻译]Coordinate System(ok)

Coordinate System·坐标系

  • Introduction of Different Coordinate Systems
    • Cartesian Coordinate System
    • UI Coordinate System
    • Direct3D Coordinate System
    • OpenGL and Cocos2d Coordinate System
  • Parent and Childrens
  • Anchor Point
  • getVisibleSize, getVisibleOrigin vs getWinSize
  • How to convert co-ordinates
    • convertToNodeSpace:
    • convertToWorldSpace:
    • convertToWorldSpaceAR,
    • Sample code:
  • References
  • Comment
## Cartesian Coordinate System

笛卡尔坐标系

### Introduction of Different Coordinate Systems·

不同坐标系简介

#### Cartesian Coordinate System·

笛卡尔坐标系

You probably have known “Cartesian Coordinate System” from school where it’s heavily used in geometry lessons. If you have forgotten, these image will remind you quickly:

你可能上学的时候就已经知道“笛卡尔坐标系”了,它在几何课本里经常用到。如果你已经忘得差不多了,下面这些图片可以很快唤起你的记忆:

There’re 3 types of coordinate system that you will meet in mobile games development.

在移动游戏开发过程中,你可能会遇到三种类型的坐标系:

#### UI Coordinate System·

UI坐标系

In common UI Coordinates on iOS/Android/Windows SDK: - The origin (x=0, y=0) is at the top-left corner. - X axis starts at the left side of the screen and increase to the right; - Y coordinates start at the top of the screen and increase downward,

iOS/Android/Windows SDK中的通用UI坐标系:

  • 起点坐标(x=0, y=0)位于左上角
  • X轴从屏幕最左边开始,由左向右渐增
  • Y轴坐标从屏幕最上方开始,由上向下渐增
looks like this

详见下图

#### Direct3D Coordinate System·

Direct3D坐标系

DirectX uses Left-handed Cartesian Coordinate.

DirectX 使用Left-handed Cartesian Coordinate(左手笛卡尔坐标系)。

#### OpenGL and Cocos2d Coordinate System

OpenGL和Cocos2d坐标系

Cocos2d-x/-html5/-iphone uses the same coordinate system as OpenGL, which is so called “Right-handed Cartesian Coordinate System”.

Cocos2d-x/-html5/-iphone使用的坐标系和OpenGL的坐标系一样,名为“Right-handed Cartesian Coordinate System”(右手笛卡尔坐标系)。

We only use x-axis & y-axis in 2D world. So in your cocos2d games: - The origin (x=0, y=0) is in the bottom-left corner of screen, which means the screen is in the first quartile of right-handed cartesian coordinate system, - X axis starts at the left side of the screen and increase to the right; - Y axis starts at the bottom of the screen and increase upwards.

在2D世界中,我们仅会使用x轴和y轴。所以在你的cocos2d游戏中:

  • 起点坐标(x=0, y=0)位于右下角,这意味着屏幕位于右手笛卡尔坐标系的第一象限
  • X轴从屏幕最左边开始,由左向右渐增
  • Y轴坐标从屏幕最下方开始,由下向上渐增
And here’s a picture that helps illustrate Cocos2d-x Coordinates a bit better:

下面这张图片有助于更好的阐述Cocos2d-x坐标:

Note that it’s different from common UI coordinate systems and DirectX coordinate systems.

一定要注意:通用UI坐标系和DirectX坐标系是不一样的。

Parent and Childrens

Every class derived from CCNode (Ultimate cocos2d-x class) will have a anchorPoint property. When determining where to draw the object (sprite, layer, whatever), cocos2d-x will combine both properties position and anchorPoint. Also, when rotating an object, cocos2d-x will rotate it around its anchorPoint.

由于每个类都继承自CCNode(cocos2d-x的最顶层类),所以每个类都会默认有anchorPoint属性。 当我们决定在一个位置画一个对象的时候,cocos2d-x会结合属性位置和anchorPoint。还有,当旋转一个对象时,cocos2d-x会绕anchorPoint旋转这个对象。

We create a sprite as a gray parent and another sprite as blue child.Set parent’s position to ccp(100,100),child’s anchor point in the center of circle .

我们创建一个灰色父对象和一个蓝色子对象。设置父对象位置是ccp(100,100),子对象的anchor point位于圆心。

1
2
3
4
5
6
7
8
9
10
11
CCSprite* parent = CCSprite::create("parent.png");
parent->setAnchorPoint(ccp(0, 0));// Anchor Point
parent->setPosition(ccp(100, 100));
parent->setAnchorPoint(ccp(0, 0));
addChild(parent);

//create child 
CCSprite* child = CCSprite::create("child.png");
child->setAnchorPoint(ccp(0.5, 0.5));
child->setPosition(ccp(0, 0));
parent->addChild(child);//add child sprite into parent sprite.
Although we set child’s position of ccp(0,0),parent’s position is ccp(100,100).Therefore,child’s position is :

由于我们设置子对象的位置是ccp(0,0),父对象位置是ccp(100,100)。所以,子对象位置如图:

### Anchor Point·

锚点

As a example, this sprite has an anchorPoint of ccp(0,0) and a position of ccp(0,0).

举个例子,下面这个精灵的锚点位于 ccp(0,0),位置位于ccp(0,0)。

This rectangle sprite will be placed at the bottom left corner of its parent, the layer. example:

这个矩形精灵将被放到它的父对象(layer)的左下角。

示例:

1
2
3
4
5
// create sprite
CCSprite* sprite = CCSprite::create("bottomleft.png");
sprite->setAnchorPoint(ccp(0, 0));// Anchor Point
sprite->setPosition(ccp(0,0));
addChild(sprite);

In another example, we will assign a anchorPoint of ccp(0.5,0.5) to better understand the relative value of the anchor point.

在另一个例子中,我们会摆放一个anchorPoint坐标为ccp(0.5,0.5)的对象,以便您更好地理解锚点的相对值。

1
2
3
4
5
// create sprite
CCSprite* sprite = CCSprite::create("center.png");
sprite->setAnchorPoint(ccp(0.5, 0.5));// Anchor Point
sprite->setPosition(ccp(0,0));
addChild(sprite);

As you can see in the image, the anchor point is not a pixel value. The value of X and Y are relative to the size of the node.

正如你从图中所见,锚点取的不是像素值,此值的X和Y是相对于此节点的大小而言。

### getVisibleSize, getVisibleOrigin vs getWinSize

获取可视区域大小, 获取可视区域起点 vs 获取窗口大小

VisibleSize returns visible size of the OpenGL view in points.The value is equal to getWinSize if don’t invoke CCEGLView::setDesignResolutionSize(). getVisibleOrigin returns visible origin of the OpenGL view in points. Please refer to [Multi resolution support](Multi resolution support) for more details

VisibleSize(可视区域大小)会返回此点OpenGL视图的可视区域大小。如果没有调用CCEGLView::setDesignResolutionSize()的话,此值等于getWinSize的大小。
getVisibleOrigin(获取可视区域起点)会返回此点OpenGL视图的可视区域起点。请移步更多支持方案查看详情。

### How to convert co-ordinates·

如何转换坐标

convertToNodeSpace:

convertToNodeSpace will be used in, for example, tile-based games, where you have a big map. convertToNodeSpace will convert your openGL touch co-ordinates to the co-ordinates of the .tmx map or anything similar. Example: The following picture shows that we have node1 with anchor point (0,0) and node2 with anchor point (1,1). We invoke CCPoint point = node1->convertToNodeSpace(node2->getPosition()); convert node2’s SCREEN coords to node1’s local.As the result,node2 with the position of (-25,-60).

举例来说,convertToNodeSpace用于tile-based的游戏,即有一个大地图。convertToNodeSpace会将openGL触摸点坐标转换成.tmx 地图或者其他近似的坐标。

例子:

下面的图片会展现,node1的锚点(0,0),node2的锚点是(1,1)。

我们调用CCPoint point = node1->convertToNodeSpace(node2->getPosition()); 相对node1的本地位置转换node2的屏幕坐标。结果node2的位置是(-25,-60).

convertToWorldSpace:

convertToWorldSpace(const CCPoint& nodePoint) converts on-node coords to SCREEN coordinates.convertToWorldSpace will always return SCREEN position of our sprite, might be very useful if you want to capture taps on your sprite but need to move/scale your layer Example:

convertToWorldSpace(常量 CCPoint& nodePoint) 转换node坐标为屏幕坐标。convertToWorldSpace通常返回精灵的屏幕位置,如果你想捕获精灵上的触摸事件却需要移动/缩放layer的时候,这可能非常有帮助。

1
CCPoint point = node1->convertToWorldSpace(node2->getPosition()); 
the above code will convert the node2‘s coordinates to the coordinates on the screen. For example if the position of node2 is (0, 0) which will be the bottom left corner of the node1, but not necessarily on the screen. This will convert (0, 0) of the node2 to the position of the screen(in this case is (15,20)). The result shows in the following picture:

上述的代码会将node2坐标转换为node2在屏幕上对应的坐标。

举个例子,如果node2的位置是(0,0),这个位置是node1的左下角,但不见得屏幕上也如此。上述代码会把(0,0)位置的node2转换到屏幕上的位置(这个例子中是(15,20))。结果如下图所示:

convertToWorldSpaceAR

convertToWorldSpaceAR will return the position relatevely to anchor point: so if our scene - root layer has Anchor Point of ccp(0.5f, 0.5f) - default, convertToWorldSpaceAR should return position relatively to screen center. convertToNodeSpaceAR - the same logic as for .convertToWorldSpaceAR

convertToWorldSpaceAR返回相对锚点的位置:所以如果你的场景 - 根layer有一个锚点位于ccp(0.5f, 0.5f)。- 默认的,convertToWorldSpaceAR应返回相对于屏幕中心的位置。

convertToNodeSpaceAR - 和convertToWorldSpaceAR是一样的逻辑。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
CCSprite *sprite1 = CCSprite::create("CloseNormal.png");

sprite1->setPosition(ccp(20,40));

sprite1->setAnchorPoint(ccp(0,0));

this->addChild(sprite1);

CCSprite *sprite2 = CCSprite::cteate("CloseNormal.png");

sprite2->setPosition(ccp(-5,-20));

sprite2->setAnchorPoint(ccp(1,1));

this->addChild(sprite2);

CCPoint point1 = sprite1->convertToNodeSpace(sprite2->getPosition());

CCPoint point2 = sprite1->convertToWorldSpace(sprite2->getPosition());

CCPoint point3 = sprite1->convertToNodeSpaceAR(sprite2->getPosition());

CCPoint point4 = sprite1->convertToWorldSpaceAR(sprite2->getPosition());

CCLog("position = (%f,%f)",point1.x,point1.y);

CCLog("position = (%f,%f)",point2.x,point2.y);

CCLog("position = (%f,%f)",point3.x,point3.y);

CCLog("position = (%f,%f)",point4.x,point4.y);

结果:

position = (-25.000000,-60.000000)
position = (15.000000,20.000000)
position = (-25.000000,-60.000000)
position = (15.000000,20.000000)

参考

Comment

[Cocos2d-x wiki翻译]Director Scene Layer and Sprite(ok)

Director Scene Layer and Sprite

Director Scene Layer and Sprite

  • Scenes
  • Director
  • Layers
  • Multiple Layers Example:
  • Sprites
  • References
  • Comment

Scenes·场景

A scene (implemented with the CCScene object) is more or less an independent piece of the app workflow. Some people may call them “screens” or “stages”. Your app can have many scenes, but only one of them is active at a given time.

场景是app工作流中一个独立的的部分。人们常常称呼它们为 “screens”或“stages”。你的app可能有很多场景,但每次你只能显示(激活)它们中的一个。

For example, you could have a game with the following scenes: Intro, Menu, Level 1, Cutscene 1, Level 2, Winning cutscene, losing cutscene, High scores screen.

比如,某个游戏有如下场景:介绍,菜单,Level 1, 画面1, Level 2, 获胜画面, 失败画面, 最高记录screen等.

You can define every one of these scenes more or less as separate apps; there is a bit of glue between them containing the logic for connecting scenes (the intro goes to the menu when interrupted or finishing, Level 1 can lead you to the cutscene 1 if finished or to the losing cutscene if you lose, etc.).

你可以定义场景为独立应用部分,通过它们包含的逻辑或连接场景(当中断或完成的时候,介绍界面会跳到菜单。如果完成,Level 1会引到你进入画面1,如果失败,Level 1会进入失败画面,等等.)将它们有机的组装起来。

-Cutscene 画面剪辑

A cocos2d CCScene is composed of one or more layers (implemented with the CCLayer object), all of them piled up. Layers give the scene an appearance and behavior; the normal use case is to just make instances of Scene with the layers that you want.

cocos2d CCScene是由一个或多个layer(通过CCLayer对象实现的)组合,堆砌而成。Layers给了场景外观和行为;常规用法是通过你想要的layers来产生场景实例。

There is also a family of CCScene classes called transitions (implemented with the CCTransitionScene object) which allow you to make transitions between two scenes (fade out/in, slide from a side, etc).

当然,CCScene家族类中也有被成为转换类(通过CCTransitionScene对象实现),它允许你在2个场景中切换( 淡出/淡入,slide动画,等待)。

Since scenes are subclasses of CCNode, they can be transformed manually or by using actions. See Actions for more detail about actions.

由于场景都是CCNode的子类,所以可以手动或者通过actions方式来改变它们,详见actions部分。

- See more at: http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Director_Scene_Layer_and_Sprite#sthash.jF0fVw56.dpuf

Director·导演类

The CCDirector is the component which takes care of going back and forth between scenes.

CCDirector是控制场景之间进出的组件。

The CCDirector is a shared (singleton) object. It knows which scene is currently active, and it handles a stack of scenes to allow things like “scene calls” (pausing a Scene and putting it on hold while another enters, and then returning to the original). The CCDirector is the one who will actually change the CCScene, after a CCLayer has asked for push, replacement or end of the current scene.

CCDirector是共享(单例)对象。它知道当前哪个场景正在显示,并且它处理 场景栈 来让 比如场景调用(暂停场景和稍待片刻进入其他入口,之后返回起始点)。

CCDirector是实际改变对象的那个,在CCLayer被询问是否入栈之后,替换或者终止当前场景的控制者。

The CCDirector is also responsible for initializing OpenGL ES.

CCDirector也可以通过初始化OpenGL ES来响应。

- See more at: http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Director_Scene_Layer_and_Sprite#sthash.jF0fVw56.dpuf

Layers·层

A CCLayer has a size of the whole drawable area, and knows how to draw itself. It can be semi transparent (having holes and/or partial transparency in some/all places), allowing to see other layers behind it. Layers are the ones defining appearance and behavior, so most of your programming time will be spent coding CCLayer subclasses that do what you need.

CCLayer有 全部可画区域的尺寸,并且知道如何去绘图。它可以半拉式渐变(),让你 去看其他位于它下方的层。Layers是定义外观和行为的,所以在你的大部分编程时间都将花费在CCLayer子类做你需要做的事情上。

The CCLayer is where you define event handlers. Events are propagated to layers (from front to back) until some layer catches the event and accepts it.

CCLayer是你定义事件处理的地方,事件会被传播到layer上(从前到后,冒泡),直到某个layer捕获此事件并接受它为止。

Although some serious apps will require you to define custom CCLayer classes, cocos2d provides a library of useful predefined layers (a simple menu layer: CCMenu, a color layer: CCColorLayer, a multiplexor between other layers: CCMultiplexLayer, and more ).

尽管一些apps会需要你去个性化定义CCLayer类,cocos2d还是提供了一个非常有用的内置预先定义好的layers(简单的菜单layer:如CCMenu,颜色layer:如CCColorLayer,在层之间多路传送的layer:如CCMultiplexLayer,等等)的类库。

Layers can contain CCSprite objects, CCLabel objects and even other CCLayer objects as children.

Layers可以包含CCSprite对象,CCLabel对象,甚至是CCLayer子对象。

Since layers are subclass of CCNode, they can be transformed manually or by using actions. See Actions for more detail about actions.

由于layers都是CCNode的子类,所以可以手动或者通过actions方式来改变它们,详见actions部分。

Multiple Layers Example:

CCLayerGradient* layer1 = CCLayerGradient::create(ccc4(255, 0, 0, 255), ccc4(255, 0, 255, 255)); 
layer1->setContentSize(CCSizeMake(80, 80)); 
layer1->setPosition(ccp(50,50)); 
addChild(layer1); 

CCLayerGradient* layer2 = CCLayerGradient::create(ccc4(0, 0, 0, 127), ccc4(255, 255, 255, 127)); 
layer2->setContentSize(CCSizeMake(80, 80)); 
layer2->setPosition(ccp(100,90)); 
addChild(layer2); 

CCLayerGradient* layer3 = CCLayerGradient::create(); 
layer3->setContentSize(CCSizeMake(80, 80)); 
layer3->setPosition(ccp(150,140)); 
layer3->setStartColor(ccc3(255, 0, 0)); 
layer3->setEndColor(ccc3(255, 0, 255)); 
layer3->setStartOpacity(255); 
layer3->setEndOpacity(255); 
ccBlendFunc blend; 
blend.src = GL_SRC_ALPHA; 
blend.dst = GL_ONE_MINUS_SRC_ALPHA; 
layer3->setBlendFunc(blend); 
addChild(layer3); 

haha

- See more at: http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Director_Scene_Layer_and_Sprite#sthash.jF0fVw56.dpuf

Sprites·精灵

A cocos2d’ sprite is like any other computer sprite. It is a 2D image that can be moved, rotated, scaled, animated, etc.

cocos2d的精灵看起来和其他计算机精灵一样。它是2D图像,可以移动,旋转,缩放,动画,等等

Sprites (implemented using the CCSprite class) can have other sprites as children. When a parent is transformed, all its children are transformed as well.

Sprites(通过使用CCSprite类实现)可以有多个其他精灵作为子对象,当父类被触发,它的所有子对象也同时被触发。

Since sprites are subclass of CCNode, they can be transformed manually or by using actions. See Actions for more detail about actions.

由于精灵都是CCNode的子类,所以可以手动或者通过actions方式来改变它们,详见actions部分。

References·参考

cocos2d for iPhone:

Comment