Cocos2d-x 3.1.1 Study Notes [18] Sprite creation tour, cocos2d-x3.1.1

Source: Internet
Author: User

Cocos2d-x 3.1.1 Study Notes [18] Sprite creation tour, cocos2d-x3.1.1


// Input a string to create an Sprite * Sprite: create (const std: string & filename) {// request a memory block from the system/* std :: when nothro has insufficient memory, new (std: nothrow) does not throw an exception, but sets the pointer to NULL. Allocation failures are very common, and they usually occur more frequently in mobile devices that do not support abnormalities. Therefore, it is safe for application developers to use nothrow new in this environment to replace common new. */Sprite * sprite = new (std: nothrow) Sprite (); // if the application is successful and the initialization is successful if (sprite & sprite-> initWithFile (filename )) {// put this sprite in the pool sprite-> autorelease ();/* Ref: autorelease () {PoolManager: getInstance ()-> getCurrentPool () -> addObject (this); return this;} */return sprite ;} // if the creation is unsuccessful, the requested memory will be safely deleted and the nullptr // # define CC_SAFE_DELETE (p) do {delete (p); (p) = nullptr;} will be returned ;} while (0) CC_SAFE_DELETE (s) Prite); return nullptr;}/* after Sprite: create (const std: string & filename) is called, the function calls Sprite: initWithFile (const std :: string & filename) */bool Sprite: initWithFile (const std: string & filename) {// asserted, filename. the size must be greater than 0. Otherwise, terminate the program/* Assert-Assert to Use assertions to create code with higher stability, better quality, and less error-prone quality. You can use assertions to interrupt the current operation when the value is FALSE. Assertions must be used for unit tests. In addition to type checks and unit tests, assertions also provide an excellent way to determine whether various features are maintained in the program. */CCASSERT (filename. size ()> 0, "Invalid filename for sprite"); // Textture Texture2D * texture = Director ctor: getInstance ()-> getTextureCache () -> addImage (filename); // if Textture if (texture) {Rect rect = Rect: ZERO; rect. size = texture-> getContentSize (); // call the specified initialization return initWithTexture (texture, rect);} // If the Textture // don't release here is not obtained. // when load texture failed, it's bett Er to get a "transparent" sprite then a crashed program // this-> release (); return false ;}/ * the bool Sprite: initWithFile (const std :: after string & filename), the function calls bool Sprite: initWithTexture (Texture2D * texture, const Rect & rect) bool Sprite: initWithTexture (Texture2D * texture, const Rect & rect) {return initWithTexture (texture, rect, false);} Then he calls another overload function bool Sprite: initWithTexture (Texture2D * Texture, const Rect & rect, bool rotated) * // designated initializerbool Sprite: initWithTexture (Texture2D * texture, const Rect & rect, bool rotated) {bool result; if (Node: init ()/* Why can I directly access this method using the class name? Because Sprite inherits Node, Sprite can call Node: init () internally. Why are both functions executed? In fact, it is only a function that executes Sprite: create (void) and calls Sprite: init (). The function of the parent class only returns true virtual bool init (); bool Node :: init () {return true;} Reimplemented in LayerMultiplex, Sprite, LayerGradient, participant system, LayerColor, transport, ControlButton, Control, transport, Layer, Menu, ClippingNode, Armature, ScrollView, DrawNode, scene, Bone, ControlColourPicker, and BatchNode. bool Sprite: init (void) {ret Urn initWithTexture (nullptr, Rect: ZERO);} */{// initialize some basic attributes _ batchNode = nullptr; _ recursiveDirty = false; setDirty (false ); _ success = true;/* const BlendFunc: ALPHA_PREMULTIPLIED = {GL_ONE, success}; # define GL_ONE 1 # define defaults 0x0303 */_ blendFunc = BlendFunc: ALPHA_PREMULTIPLIED; _ flippedX = _ flippedY = false; // default transform anchor: Center // The default anchorPoint is set to (0.5, 0.5) here. SetAnchorPoint (Vec2 (0.5f, 0.5f); // zwoptex default values _ offsetPosition = Vec2: ZERO; // clean the Quad/* void * memset (void * s, int ch, size_t n); function explanation: Replace the first n Bytes (typedef unsigned int size_t) in s with ch and return s. Memset: fills in a given value in a memory block. It is the fastest way to perform the clearing operation on a large struct or array. */Memset (& _ quad, 0, sizeof (_ quad); // Atlas: Color/* // vertex coordinate, texture coordinate and Color information // vertex coords, texture coords and color info V3F_C4B_T2F_Quad _ quad ;//! 4 Vertex3FTex2FColor4B struct V3F_C4B_T2F_Quad {//! Top left V3F_C4B_T2F tl ;//! Bottom left V3F_C4B_T2F bl ;//! Top right V3F_C4B_T2F tr ;//! Bottom right V3F_C4B_T2F br ;};//! A Vec2 with a vertex point, a tex coord point and a color 4B struct V3F_C4B_T2F {//! Vertices (3F) Vec3 vertices; // 12 bytes //! Colors (4B) Color4B colors; // 4 bytes // tex coords (2F) Tex2F texCoords; // 8 bytes}; */_ quad. bl. colors = Color4B: WHITE; _ quad.br. colors = Color4B: WHITE; _ quad. tl. colors = Color4B: WHITE; _ quad. tr. colors = Color4B: WHITE;/* void Node: setGLProgramState (cocos2d: GLProgramState * glProgramState) {if (glProgramState! = _ GlProgramState) {// # define CC_SAFE_RELEASE (p) do {if (p) {(p)-> release () ;}} while (0) CC_SAFE_RELEASE (_ glProgramState); _ glProgramState = glProgramState; // # define CC_SAFE_RETAIN (p) do {if (p) {(p)-> retain ();}} while (0) CC_SAFE_RETAIN (_ glProgramState) ;}} * // shader state setGLProgramState (GLProgramState: getOrCreateWithGLProgramName (GLProgram: Unknown) ); SetTexture (texture); setTextureRect (rect, rotated, rect. size); // by default use "Self Render ". // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render" setBatchNode (nullptr); result = true;} else {result = false ;} _ recursiveDirty = true; setDirty (true); return result;}/* bool Sprite: initWithTexture (Texture2D * texture, const Rect & rect, bool rotated) Void Sprite: setTexture (Texture2D * texture) */void Sprite: setTexture (Texture2D * texture) {// If batchnode, then texture id shocould be the same CCASSERT (! _ BatchNode | texture-> getName () = _ batchNode-> getTexture ()-> getName (), "CCSprite: batched sprites shocould use the same texture as the batchnode "); // accept texture = nil as argument/* dynamic_cast <type-id> (expression) this operator converts expression to type-id objects. Type-id must be a class pointer, class reference, or void *. If type-id is a class pointer Type, expression must also be a pointer, if type-id is a reference, expression must also be a reference. The dynamic_cast operator can determine the real type during the execution period. If downcast is secure (that is, if the base class pointer or reference actually points to a derived class Object), the operator returns a pointer that has been transformed as appropriate. If downcast is not secure, this operator returns a null pointer (that is, the base class pointer or reference does not point to a derived class Object) */CCASSERT (! Texture | dynamic_cast <Texture2D *> (texture), "setTexture expects a Texture2D. invalid argument "); // if Texture is empty, create if (texture = nullptr) {// Gets the texture by key firstly. texture = Director: getInstance ()-> getTextureCache ()-> getTextureForKey (CC_2x2_WHITE_IMAGE_KEY); // If texture wasn't in cache, create it from RAW data. if (texture = nullptr) {Image * image = new Image (); bool isOK = im Age-> initWithRawData (cc_2x2_white_image, sizeof (cc_2x2_white_image), 2, 2, 8); reset (isOK); CCASSERT (isOK, "The 2x2 empty texture was created handle. "); texture = Director: getInstance ()-> getTextureCache ()-> addImage (image, CC_2x2_WHITE_IMAGE_KEY); CC_SAFE_RELEASE (image );}} /* if it is not a batchnode and textture (nullptr by default) is different from the original Sprite: Sprite (void): _ shouldBeHidden (false), _ texture (nu Llptr), _ insideBounds (true) {}*/if (! _ BatchNode & _ texture! = Texture) {CC_SAFE_RETAIN (texture); CC_SAFE_RELEASE (_ texture); _ texture = texture; updateBlendFunc () ;}} void Sprite: updateBlendFunc (void) {CCASSERT (! _ BatchNode, "CCSprite: updateBlendFunc doesn't work when the sprite is rendered using a SpriteBatchNode"); // it is possible to have an untextured sprite if (! _ Texture |! _ Texture-> hasPremultipliedAlpha () {_ blendFunc = BlendFunc: Upper; lower (false);} else {_ blendFunc = BlendFunc: ALPHA_PREMULTIPLIED; lower (true );}} void Sprite: setTextureRect (const Rect & rect, bool rotated, const Size & untrimmedSize) {_ rectRotated = rotated; setContentSize (untrimmedSize ); // setVertexRect (rect); // setTextureC Oords (rect); Vec2 relativeOffset = _ unflippedOffsetPositionFromCenter; // issue #732 if (_ flippedX) {relativeOffset. x =-relativeOffset. x;} if (_ flippedY) {relativeOffset. y =-relativeOffset. y;} _ offsetPosition. x = relativeOffset. x + (_ contentSize. width-_ rect. size. width)/2; _ offsetPosition. y = relativeOffset. y + (_ contentSize. height-_ rect. size. height)/2; // rendering using batch node I F (_ batchNode) {// update dirty _, don't update recursiveDirty _ setDirty (true);} else {// self rendering/Atlas: vertex float x1 = 0 + _ offsetPosition. x; float y1 = 0 + _ offsetPosition. y; float x2 = x1 + _ rect. size. width; float y2 = y1 + _ rect. size. height; // Don't update Z. _ quad. bl. vertices = Vec3 (x1, y1, 0); _ quad.br. vertices = Vec3 (x2, y1, 0); _ quad. tl. vertices = Vec3 (x1, y2, 0); _ quad. tr. Vertices = Vec3 (x2, y2, 0) ;}} void Ref: release () {CCASSERT (_ referenceCount> 0, "reference count shold greater than 0 "); -- _ referenceCount; // if it is equal to 0, check whether it should be removed. if (_ referenceCount = 0) {# if defined (COCOS2D_DEBUG) & (COCOS2D_DEBUG> 0) auto poolManager = PoolManager: getInstance (); // checks whether the caller exists in the auto Release pool. If the consumer is in the auto Release pool, the count value must be greater than or equal to 1, the assertion if (! PoolManager-> getCurrentPool ()-> isClearing () & poolManager-> isObjectInPools (this )) {// Trigger an assert if the reference count is 0 but the Ref is still in autorelease pool. // This happens when 'autorelease/release 'were not used in pairs with 'new/reta '. /// Wrong usage (1): // auto obj = Node: create (); // Ref = 1, but it's an autorelease Ref which means it was in the autorelease pool. // Obj-> autorelease (); // Wrong: If you want to invoke autorelease several times, you shoshould retain 'obj 'first. /// Wrong usage (2): // auto obj = Node: create (); // obj-> release (); // Wrong: obj is an autorelsponref, it will be released when clearing current pool. /// Correct usage (1): // auto obj = Node: create (); // |-new Node (); // 'new' is the pair of the 'autorelogy' of next l Ine // |-autorelease (); // The pair of 'new node '. /// obj-> retain (); // obj-> autorelease (); // This 'autorelist' is the pair of 'reta' of previous line. /// Correct usage (2): // auto obj = Node: create (); // obj-> retain (); // obj-> release (); // This 'release' is the pair of 'reta' of previous line. CCASSERT (false, "The reference shouldn't be 0 because it is still in autorelease pool. ") ;}# Endif // function is equivalent to a switch. Modify the macro definition as needed and execute corresponding processing. // This macro is disabled by default. // # define CC_USE_MEM_LEAK_DETECTION 0 // Memory leakage detection # if CC_USE_MEM_LEAK_DETECTION untrackRef (this); # endif // if count is 0, delete this;} Sprite: create (const std: string & filename)-> Sprite: initWithFile (const std :: string & filename)-> Sprite: initWithTexture (Texture2D * texture, const Rect & rect, bool rotated)-> setTexture (texture);-> Sprite: updateBlendFunc (void) -> setTextureRect (rect, rotated, rect. size );









Notes on: http://blog.csdn.net/zhouyunxuan


Cocos2d-x how to specify Sprite jitter effect!

Let Sprite execute the Rotation animation infinitely to achieve the jitter effect.
Hope to help you.
 
How can cocos2d control the size of the sprite image?

Use the Scale value of CCSptite to set the size. If it is 1.0, how can it reduce the size of the original image texture by 1 or more?

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.