【cocos2d-js官方文档】十八、Cocos2d-JS v3.0中的属性风格API

前端之家收集整理的这篇文章主要介绍了【cocos2d-js官方文档】十八、Cocos2d-JS v3.0中的属性风格API前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1. 新的API风格

我们直接来看看你可以如何使用Cocos2d-JS v3.0:@H_502_3@

以前的API 新的API
node.setPosition(x,y); node.x = x;
node.y = y;
node.setRotation(r); node.rotation = r;

如表格中可以看到的,设置position属性函数调用在3.0版中会被替换为直接的对象属性存取。不仅仅是示例中的xyrotation,几乎所有节点类型中关于属性存取的函数都会被替换为直接的对象属性访问。具体的属性列表在文档最后。@H_502_3@

得益于JavaScript的getter/setter,我们可以为对象的某一个属性名分别设置其getter/setter函数。这就是Cocos2d-JS如何做到从函数属性的转换。比如说,node.x = x;实际上调用setPositionX函数并传入x作为参数,所以在使用属性风格API的时候请不要因为它的简单而感到担心,在很多情况下这等同于以前的函数调用。@H_502_3@

你也可以给自己的对象属性定义getter/setter函数,只需要使用下面这行代码:@H_502_3@

cc.defineGetterSetter(object,"propertyName",getterFunc,setterFunc);

这样的话,var a = object.propertyName;会通过getterFunc获取propertyName的当前值,object.propertyName = newvalue;则会通过setterFunc来给propertyName赋新值。@H_502_3@

至于属性的命名,我们尽可能提供了类似css风格的属性名,除此之外的属性都尽力维持与v2.2.2中一致。选择类似css的属性名是为了给JavaScript开发者以最自然的开发体验。@H_502_3@

2. cc.Node的attr函数

新API使得Cocos2d-JS代码更加简洁,但这还不够,我们为cc.Node添加了更为简单易用的attr函数。与jQuery的attr函数相同,这个函数允许开发者批量设置多个属性。示例如下:@H_502_3@

node.attr({
    x: 20,y0.5,anchorY400,height300,scale2
});

值得一提的是,这个函数不仅仅支持文末列表中的属性,也支持开发者的自定义属性。@H_502_3@

3. 改变的初衷

为什么Cocos2d-JS要对已稳定的API做出如此大的改变呢?我想最显而易见的答案已经体现在前面的示例中了:那就是更简单。@H_502_3@

但是我们真正想改变的目标,并不仅仅是更简单而已,或者说简单并不是目标,而是结果。长期以来,Cocos2d-JS一直被WEB开发者诟病其复杂程度导致难于学习和使用。在与其他html5游戏引擎比较之后,我们发现我们引擎最大的问题是,它并不是为JavaScript开发者设计的。事实上确实如此,到目前为止,Cocos2d-JS引擎的实现目标一直是尽力与Cocos2d-x的API保持一致,而Cocos2d-x是为C++开发者设计的,与此同时,Cocos2d家族的起源Cocos2d-iPhone也在引擎中留下了非常多objective-C风格的API设计。很显然,正是由于这些API被直接移植到h5引擎中,JavaScript开发者才会觉得引擎非常复杂难用。@H_502_3@

所以引擎3.0版本的主要目标就是提供给开发者一套全新的JavaScript风格API,开发团队决定冒着很大的风险推动这次重构。@H_502_3@

回到属性风格API,cc.Node以及所有继承自cc.Node的类都使用属性风格重构。以往的大多数getXXX()setXXX(value)都被直接属性存取取代了。同时也有也有少数其他适合属性风格的类使用这种方式重构,它们都可以在文末的列表中找到。@H_502_3@

4. 关于Closure Compiler

由于attr函数使用键值对来配置节点,当我们使用Closure Compiler的高级模式来混淆时,这可能会引起一些意想不到的错误。@H_502_3@

简单来说,键值对中的键实质上是String类型,混淆过程中它并不会被压缩,而与之相对应的属性名却会被压缩,这导致了两者命名的不匹配。所幸,在引擎中我们保障了常用的属性不会被压缩,至于其他的属性用户自定义属性,可以使用Closure Compiler的expose声明来避免出现问题。需要注意的是这个问题只有在开发者尝试使用attr函数来配置属性的时候才会出现,如果没有使用attr函数就不需要做任何额外的处理。@H_502_3@

/** @expose */ node.shaderProgram; /** @expose */ node.customProperty; node.attr({ shaderProgram: program,customProperty0 });

5. 通过继承来重载属性

另一个重要的问题是在继承过程中,如何重载父类中的属性。好消息是我们已经将这一机制在Cocos2d-JS的cc.Class中实现了。只要你重载了父类中的getter/setter函数,那么不需要重新定义,新的getter/setter会自动被绑定到属性上。下面是一个重载Sprite类中的x属性的例子:@H_502_3@

var MySprite = cc.Sprite.extend({ ctor: function() { this._super(); this.init(); },getPositionX: function() { // Your own implementation },163)">setPositionX: function(x) { // Your own implementation } }); var mySprite = new MySprite();

mySprite.x = x;调用MySprite类的setPositionX函数而不是Sprite类的,getter函数也是同理。用户代码中唯一需要保证的是重载的getter/setter函数名必须和父类中定义的属性的getter/setter函数同名。否则你将需要通过cc.defineGetterSetter重新定义属性。@H_502_3@

6. 属性列表

cc.Node

shaderProgram
Property Type Accessibility Getter/Setter function Advanced Compress Ready
x Number R&W getPositionX,setPositionX YES
y getPositionY,setPositionY width _getWidth,_setWidth height _getHeight,_setHeight anchorX _getAnchorX,_setAnchorX anchorY _getAnchorY,_setAnchorY skewX getSkewX,setSkewX skewY getSkewY,setSkewY zIndex getLocalZOrder,setLocalZOrder vertexZ getVertexZ,setVertexZ rotation getRotation,setRotation rotationX getRotationX,setRotationX rotationY getRotationY,setRotationY scale getScale,setScale scaleX getScaleX,setScaleX scaleY getScaleY,setScaleY opacity getOpacity,setOpacity opacityModifyRGB Boolean isOpacityModifyRGB,setOpacityModifyRGB cascadeOpacity isCascadeOpacityEnabled,setCascadeOpacityEnabled color cc.Color getColor,setColor cascadeColor isCascadeColorEnabled,setCascadeColorEnabled children Array readonly getChildren childrenCount getChildrenCount parent cc.Node getParent,setParent visible isVisible,setVisible running isRunning ignoreAnchor isIgnoreAnchorPointForPosition,ignoreAnchorPointForPosition tag None userData Object userObject arrivalOrder actionManager cc.ActionManager getActionManager,setActionManager scheduler cc.Scheduler getScheduler,setScheduler grid cc.GridBase NO
cc.GLProgram getShaderProgram,setShaderProgram YES

cc.Texture2D

name
WebGLTexture getName pixelFormat getPixelFormat pixelsWidth getPixelsWide pixelsHeight getPixelsHigh maxS maxT NO

cc.Sprite

Extend from cc.NodeRGBA@H_502_3@

dirty
flippedX isFlippedX,setFlippedX flippedY isFlippedY,setFlippedY offsetX _getOffsetX offsetY _getOffsetY atlasIndex texture cc.Texture2D getTexture,setTexture textureRectRotated isTextureRectRotated textureAtlas cc.TextureAtlas batchNode cc.SpriteBatchNode getBatchNode,setBatchNode quad cc.V3F_C4B_T2F_Quad getQuad cc.LabelTTF

Extend from cc.Sprite@H_502_3@

@H_502_3@

string
String getString,setString textAlign getHorizontalAlignment,setHorizontalAlignment verticalAlign getVerticalAlignment,setVerticalAlignment fontSize getFontSize,setFontSize fontName getFontName,setFontName font _getFont,_setFont boundingWidth _getBoundingWidth,_setBoundingWidth boundingHeight _getBoundingHeight,_setBoundingHeight fillStyle _getFillStyle,setFontFillColor strokeStyle _getStrokeStyle,_setStrokeStyle lineWidth _getLineWidth,_setLineWidth shadowOffsetX _getShadowOffsetX,_setShadowOffsetX shadowOffsetY _getShadowOffsetY,_setShadowOffsetY shadowOpacity _getShadowOpacity,_setShadowOpacity shadowBlur _getShadowBlur,_setShadowBlur YES

cc.Node

cc.TextureAtlas
Image
capacity getCapacity totalQuads getTotalQuads quads getQuads,setQuads cc.AtlasNode

quadsToDraw

cc.LayerRGBA

Extend from cc.Layer@H_502_3@

cc.LayerGradient

Extend from cc.LayerColor@H_502_3@

startColor
getStartColor,setStartColor endColor getEndColor,setEndColor startOpacity getStartOpacity,setStartOpacity endOpacity getEndOpacity,setEndOpacity vector getVector,setVector compresseInterpolation cc.ClippingNode

Extend from cc.Node@H_502_3@

alphaThreshold
inverted stencil getStencil,setStencil cc.SpriteBatchNode

descendants

getDescendants Extend from cc.Sprite

cc.LabelAtlas

Extend from cc.AtlasNode@H_502_3@

cc.LabelBMFont

Extend from cc.SpriteBatchNode@H_502_3@

enum
_getAlignment,setAlignment cc.Menu

Extend from cc.LayerRGBA@H_502_3@

enabled
cc.MenuItem

isEnabled,setEnabled

cc.MenuItemLabel

Extend from cc.MenuItem@H_502_3@

label
getLabel,setLabel disabledColor getDisabledColor,setDisabledColor cc.MenuItemFont

Extend from cc.MenuItemLabel@H_502_3@

cc.MenuItemSprite

normalImage

cc.Sprite getNormalImage,setNormalImage selectedImage getSelectedImage,setSelectedImage disabledImage getDisabledImage,setDisabledImage cc.NodeGrid

target

writeonly setTarget cc.ParticleBatchNode

cc.ParticleSystem

active

isActive shapeType particleCount duration sourcePos cc.Point getSourcePosition,setSourcePosition posVar getPosVar,setPosVar life lifeVar angle angleVar startSize startSizeVar endSize endSizeVar startSpin startSpinVar endSpin endSpinVar gravity getGravity,setGravity speed getSpeed,setSpeed speedVar getSpeedVar,setSpeedVar tangentialAccel tangentialAccelVar getTangentialAccel,setTangentialAccel getTangentialAccelVar,setTangentialAccelVar rotationIsDir getRotationIsDir,setRotationIsDir startRadius getStartRadius,setStartRadius startRadiusVar getStartRadiusVar,setStartRadiusVar endRadius getEndRadius,setEndRadius endRadiusVar getEndRadiusVar,setEndRadiusVar rotatePerS getRotatePerSecond,setRotatePerSecond rotatePerSVar getRotatePerSecondVar,setRotatePerSecondVar startColorVar getStartColorVar,setStartColorVar endColorVar getEndColorVar,setEndColorVar emissionRate emitterMode positionType totalParticles getTotalParticles,setTotalParticles autoRemoveOnFinish cc.ProgressTimer

midPoint

getMidpoint,setMidpoint barChangeRate getBarChangeRate,setBarChangeRate type getType,setType percentage getPercentage,setPercentage sprite getSprite,setSprite reverseDir isReverseDirection,setReverseDirection cc.RenderTexture

clearFlags

clearDepthVal clearStencilVal clearColorVal getClearColor,setClearColor autoDraw cc.TMXLayer

tiles

tileset cc.TMXTilesetInfo layerOrientation properties layerName layerWidth _getLayerWidth,_setLayerWidth layerHeight _getLayerHeight,_setLayerHeight tileWidth _getTileWidth,_setTileWidth tileHeight _getTileHeight,_setTileHeight cc.TMXTiledMap

mapOrientation

objectGroups mapWidth _getMapWidth,_setMapWidth mapHeight _getMapHeight,_setMapHeight ccui.Widget

Extend from ccui.Node@H_502_3@

xPercent
_getXPercent,_setXPercent yPercent _getYPercent,_setYPercent widthPercent _getWidthPercent,_setWidthPercent heightPercent _getHeightPercent,_setHeightPercent widgetParent ccui.Widget getWidgetParent focused isFocused,setFocused touchEnabled isTouchEnabled,setTouchEnabled updateEnabled isUpdateEnabled,setUpdateEnabled bright isBright,setBright getName,setName actionTag getActionTag,setActionTag ccui.Layout

Extend from ccui.Widget@H_502_3@

clippingEnabled
isClippingEnabled,setClippingEnabled ccui.Button

titleText

getTitleText,setTitleText titleFont _getTitleFont,_setTitleFont titleFontSize getTitleFontSize,setTitleFontSize titleFontName getTitleFontName,setTitleFontName titleFontColor pressedActionEnabled ccui.CheckBox

selected

getSelectedState,setSelectedState ccui.LoadingBar

percent

getPercent,setPercent ccui.Slider

ccui.Text

getStringValue,setText

stringLength getStringLength getTextHorizontalAlignment,setTextHorizontalAlignment getTextVerticalAlignment,setTextVerticalAlignment touchScaleEnabled ccui.TextAtlas

ccui.TextBMFont

ccui.TextField

maxLengthEnabled

isMaxLengthEnabled,setMaxLengthEnabled maxLength getMaxLength,setMaxLength passwordEnabled isPasswordEnabled,setPasswordEnabled ccui.ScrollView

Extend from ccui.Layout@H_502_3@

innerWidth
_getInnerWidth,_setInnerWidth innerHeight _getInnerHeight,_setInnerHeight bounceEnabled inertiaScrollEnabled ccs.Armature

Extend from ccs.NodeRGBA@H_502_3@

parentBone
ccs.Bone getParentBone,setParentBone animation ccs.ArmatureAnimation armatureData ccs.ArmatureData version body getBody,setBody colliderFilter ccs.ColliderFilter setColliderFilter ccs.Bone

boneData

ccs.BoneData getBoneData,setBoneData armature ccs.Armature getArmature,setArmature childArmature getChildArmature,setChildArmature childrenBone getChildrenBone tween ccs.Tween getTween tweenData ccs.FrameData getTweenData transformDirty getColliderFilter,setColliderFilter displayManager ccs.DisplayManager ignoreMovementBoneData blendDirty ccs.Skin

Extend from ccs.Sprite@H_502_3@

skinData
getSkinData,setSkinData bone displayName getDisplayName cc.EditBox

Extend from cc.ControlButton@H_502_3@

_setFont
setFontName setFontSize getText,sans-serif"> cc.Control

state

getState isSelected,setSelected highlighted isHighlighted,setHighlighted cc.ControlButton

Extend from cc.Control@H_502_3@

adjustBackgroundImage
zoomOnTouchDown preferredSize cc.Size getPreferredSize,setPreferredSize labelAnchor getLabelAnchorPoint,setLabelAnchorPoint cc.ControlColourPicker

background

getBackground cc.ControlHuePicker

hue

getHue,setHue huePercent getHuePercentage,setHuePercentage slider getSlider startPos getStartPos cc.ControlPotentiometer

value

getValue,setValue minValue getMinimumValue,setMinimumValue maxValue getMaximumValue,setMaximumValue progressTimer cc.ProgressTimer getProgressTimer,setProgressTimer thumbSprite getThumbSprite,setThumbSprite prevLocation getPrevIoUsLocation,setPrevIoUsLocation cc.ControlSaturationBrightnessPicker

saturation

getSaturation brightness getBrightness overlay getOverlay shadow getShadow cc.ControlSlider

minAllowedValue

getMinimumAllowedValue,setMinimumAllowedValue maxAllowedValue getMaximumAllowedValue,setMaximumAllowedValue getThumbSprite progressSprite getProgressSprite backgroundSprite getBackgroundSprite cc.ControlStepper

wraps

getWraps,setWraps stepValue getStepValue,setStepValue continuous isContinuous minusSprite getMinusSprite,setMinusSprite plusSprite getPlusSprite,setPlusSprite minusLabel cc.LabelTTF getMinusLabel,setMinusLabel plusSLabel cc.Scale9Sprite

capInsets

cc.Rect getCapInsets,setCapInsets insetLeft getInsetLeft,setInsetLeft insetTop getInsetTop,setInsetTop insetRight getInsetRight,setInsetRight insetBottom getInsetBottom,setInsetBottom cc.TableViewCell

Extend from cc.Node@H_502_3@

objectId
getObjectID,setObjectID YES
转载 请注明: http://www.cocos2dx.net/post/235

猜你在找的Cocos2d-x相关文章