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.

I'm developing a game in XNA(C#) and I wonder what are the best practices for having different types of pads. For example I have 2 types of pads:

  • Pad that just moves left (decreasing X coordinate)
  • Pad moves left and moves up and down (cos function on Y coordinate)

Later I would like to implement more pads. I know I could check type in Update method and do a proper method for updating but I think it could be done better. I have the Pads class:

class Pads
    static list of pads;
    public void draw();
    public static void drawAll(); //Iterate through list and draw each item
    public void update();
    public static void updateAll(); //Iterate through list and update each item

Should I create another class for example cosPad which would extend Pads?

I really don't have idea how to make everything logical.

share|improve this question

2 Answers 2

If the pads are only different in their movement/behavior I would create a separate class to control this and use composition to get the desired effect.

public class Pad : GameObject{
    Vector2 Position;
    Behavior B;

    Update(GameTime t){
        B.Update(this, t);
    }
}

public class Slide : Behavior{
    Update(GameObject o, GameTime t){
        o.Position.X = sin(t);
    }
}

public class Circle : Behavior{
    Update(GameObject o, GameTime t){
        o.Position.X = sin(t);
        o.Position.Y = cos(t);
    }
}
share|improve this answer
1  
+1 for showing alternative to inheritance. –  George Duckett Apr 27 '12 at 10:41
1  
+1 for composition :D –  Gustavo Maciel Apr 27 '12 at 12:07
    
I really don't understand B.Update(this, t) What do we put when we are initializing new pad? Behavior B = new Slide()? –  user1188570 Apr 27 '12 at 14:32
    
No, more like Pad P = new Pad(); P.B = new Circle(); (ok the naming is a bit akward but you get the point) –  Roy T. Apr 27 '12 at 14:45
    
Thanks, got the idea :) –  user1188570 Apr 27 '12 at 15:09

You could create an abstract class Pad that represents a moveable pad, then your Pads class would have a list of these Pads.

The Pad class could have an implemented draw method if that was common to both, and an abstract Update(GameTime) method.

You'd derive your 2 concrete classes PadMoveLeft and PadCosine from Pad which would implement Update.

share|improve this answer

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.