Skip to main content
4 of 4
added ploymorphism tag
Tetrad
  • 30.1k
  • 12
  • 96
  • 143

How to handle similar actions in derived actors (inheritance)

I have a base class called Attacker that has a update method. The update method moves attacker through an array of waypoints as given below:

- (void) update:(ccTime)dt {
    if(state == kMove) {
        // code to move to next waypoint
        // on reaching the next waypoint, update the next waypoint variable
        // if the final waypoint is reached, then stop the movement of attacker
    }
}

So, the base class takes care of simple waypoint movement logic. Now I derive a few classes like Rifleman, MachineGunner, Engineer from the Attacker class.

Now I want each of the derived class to do a specific action on reaching the final waypoint. For eg., I want the Rifleman to change to attack stance, the machine gunner to deploy and setup his gun, the engineer to start constructing a defense.

How do I achieve this? My current idea is to check for final waypoint condition in the update method of each of the derived class and do the corresponding action.

- (void) update:(ccTime)dt {
    [super update:dt];
    if(state == kMove) {
        // if the final waypoint is reached, then do class specific action
    }
}

Is there any better way of doing this?

saiy2k
  • 486
  • 4
  • 12