I am very new to C#, XNA, and OOP. This is my question: I have an abstract class called Sprite. Sprite handles position and drawing from the sprite sheets, from its update and draw methods, for my other automated and user controlled classes. I have another class that I need to create that also uses a sprite sheet but not in the same way. The sprite sheet in this case shows the texture in 5 states, from whole to destroyed, and I am going to write the update method for it so that when a missile collides with the texture, then and only then does the next frame of the sprite sheet get drawn. Is there a way that I can have this class, called bunker, be a child of the sprite class but never call the update method from the parent? Or should I just make it a seperate class altogether? Thank you for bearing with my noobish question.
1 Answer
\$\begingroup\$
\$\endgroup\$
5
There are many ways to do that like using interfaces,abstract classes, etc. But you can use virtual methods. You can make the update method of Sprite class "virtual" like this:
public virtual void update()
{ // code for sprite update
}
And then in bunker class you should override update method and change it from what it was in sprite class :
class Bunker: Sprite
{
...
public override void update()
{//here your update code
//different
//from base(Sprite) class}
}
-
\$\begingroup\$ One question to be clear, in the bunker update method, am I still including the line
base.Update();? I assume that I need to and it gets sorted out with the virtual keyword... I am going to write it now. Thank you very much. \$\endgroup\$Sinux1– Sinux12016-07-11 08:00:25 +00:00Commented Jul 11, 2016 at 8:00 -
\$\begingroup\$ @Sinux1 if you want sprite.update() method to be called in addition to bunker.update(), you should add base.update() in bunker update method. \$\endgroup\$klaymen– klaymen2016-07-11 08:29:23 +00:00Commented Jul 11, 2016 at 8:29
-
\$\begingroup\$ But that would mean that the base update would also run, right? I don't want that . Thank you. \$\endgroup\$Sinux1– Sinux12016-07-11 08:34:40 +00:00Commented Jul 11, 2016 at 8:34
-
1\$\begingroup\$ @Sinux1 It seems like you want the
Spriteclass to beabstractand then have your "not-Bunker" objects be another class inheriting fromSprite. You would then have all code which is common to all sprites inSpriteand all object-specific code in the derived classes. \$\endgroup\$Philipp– Philipp2016-07-11 08:56:46 +00:00Commented Jul 11, 2016 at 8:56 -
\$\begingroup\$ @Philipp Yes, I made Sprite abstract. I've got some automated enemies and a player who all derive from the sprite class. I appreciate all the help. This SE is awesome. \$\endgroup\$Sinux1– Sinux12016-07-11 09:17:38 +00:00Commented Jul 11, 2016 at 9:17