Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
1  
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. –  Ali.S Sep 30 '11 at 13:07
3  
This code shows a severe deficiency at basic understanding of Java and OO, and so is probably off-topic. –  user744 Sep 30 '11 at 13:24
    
by the way you can can't cast result of CCSprite constructor to CharacterSprite! –  Ali.S Sep 30 '11 at 14:25
    
@Joe He is a newbie, he'll get subclassing (...) after some time. –  user712092 Oct 12 '11 at 2:23
add comment

1 Answer 1

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.