0
\$\begingroup\$

Can someone tell me how to subclass CCSprite on Android?

I've added this snippet of code into my CharacterSprite:

public static CharacterSprite sprite(String fileName) {
  return new (CharacterSprite)CCSprite(
    CCTextureCache.sharedTextureCache().getTexture(fileName)
  );
}

But getTexture() can't be found. Can someone help me please?

\$\endgroup\$
4
  • 1
    \$\begingroup\$ are you sure it's only getTexture that can't be found. isn't there any problem with CCTextureCache? by the way I'm not sure if it does apply to java ba usually you can't override static methods. \$\endgroup\$
    – Ali1S232
    Sep 30 '11 at 13:07
  • 3
    \$\begingroup\$ This code shows a severe deficiency at basic understanding of Java and OO, and so is probably off-topic. \$\endgroup\$
    – user744
    Sep 30 '11 at 13:24
  • \$\begingroup\$ by the way you can can't cast result of CCSprite constructor to CharacterSprite! \$\endgroup\$
    – Ali1S232
    Sep 30 '11 at 14:25
  • \$\begingroup\$ @Joe He is a newbie, he'll get subclassing (...) after some time. \$\endgroup\$
    – user712092
    Oct 12 '11 at 2:23
4
\$\begingroup\$

Here is the way generally followed to sub-class a CCSprite.

    public class CharacterSprite extends CCSprite
     {
        // Add new custom fields or methods here,
        // or override the specific methods of CCSprite 
        // that you want to extend the functionality of.
     }

From your question I can understand that you are inheriting CCSprite not to extend the functionality. Usually this should be avoided. There is no need to override the public static CharacterSprite sprite(String fileName) method as it will be already there in the super class.

So a call like this will do: CharacterSprite.sprite("sample.png"). This will return a sprite you desire!

In fact, There are two ways you can make CharacterSprite class which you desire.

  1. Inheriting CCSprite. Do this only if you are really over-riding any functionality of the existing CCSprite (for example, if you want to draw with multi-texturing , override draw and have your code).

  2. Have CCSprite instance as an attribute (member) of CharacterrSprite class. This is the better way if you are "not re-defining" the functionality of CCSprite.

For example, the second case will be like this:

 class CharacterSprite
 {
   Position m_pos; 
   // ...
   CCSprite m_sprite; // The sprite instance.

   CharacterSprite(String filename)
   {
     m_sprite = new CCSprite(filename);
   }  
 }   

 // Usage:
 CharacterSprite _character = new CharacterSprite("character.png");

Now add _character.m_sprite to the current scene/layer.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .