简体   繁体   中英

How to copy instances of an extended CCSprite?

I'm planning to extend the CCSprite class in order to create a Block class, which are the basic building blocks of my game. There may be a number of "archblocks" - prototypes on which individual blocks are to be based. In particular, I want to create a palette, from which the user can pick her building blocks which are to be placed on the game board. Once placed on the board, the building blocks takes on an identity of it's own.

Here's what I have so far:

class Block : public CCSprite {
private:
  int _id = 0;
  int _type = 0;
public:
  Block* CopyBlock();
}

Once a user selects a Block and drops it on the game board, CopyBlock is going to be invoked and the prototype be safely returned to the palette, leaving the newly minted Block living a life of its own on the game board.

I've noticed that CCObject "implements" a Copy method, but as far as I can tell this just refers to a CopyWithZone(0) for CCObject that isn't implemented. The Copy method isn't virtual, though, so I'm a little unsure if I'm able to override this. (I'm not super strong in C++ but I do have a good grasp on OOP, so I'm up for the details if anyone care to share.)

Question:

1) Does this design make sense? Should I go with overriding Copy and/or CopyWithZone instead?

2) How can I implement CopyBlock (or Copy and/or CopyWithZone ) so that both CCSprite stuff and members like _type are copied to the new Block ?

Thanks!

Unless your block sprite contains children. You can easily create a copy constructor, creating the same sprite and copying the block's attributes (and maybe some needed sprite attributes) by yourself :

class Block : public CCSprite {
private:
  int _id = 0;
  int _type = 0;
public:
  Block (Block &otherBlock);
}

Implementation file :

Block::Block (Block &otherBlock) {
   this->initWithTexture(otherBlock.getTexture());
   // If your sprite contains children then this is the place to iterate all children
   // sprites, create and add them to this block. (do not forget to copy their position as well.)
   this->_id = otherBlock._id;
   this->_type = otherBlock._type;
}

Note that since initWithTexture does not copy the texture, if you tweak the texture it will be visible on all copies of blocks but if you don't have texture tweaking needs then this should work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM