-1

I created a class for a type of enemy using allegro4 and C++; in this class I have a function that makes move a sprite, like this:

sprite_one(x, y); 
sprite_two(x2, y2);

class enemy{
    public:
    void mov(){
            x++;
            ----
            y--;
        }
    }        
};


enemy test_one;
test_one.mov();    // this works because its coordinates are x and y

enemy test_two;
test_two.mov();    // this doesn't work, its coordinates are x2 and y2 

The problem is that when I create the object, the first one can move according to the function (updating variable x and y), the others no because they have different way to call the variables of the positions. How can I fix this?

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • 1
    First of all, what are `x` and `y`? They _look_ like global variables, but object oriented design principles say that they should be member variables of `class enemy`, meaning that each `enemy` can have its own coordinates. Second.... what is this `----` doing in the middle of the `mov` function? That should be in a comment, not interfering with the next line of code. – Tim Randall Feb 15 '19 at 19:30
  • In the middle of the function there are only increases and decreases of the variables. I created int x and int y as global variables, same things for x2 and y2. Should I declare them in the function? – jhon k. Feb 15 '19 at 19:34
  • I think you need to search for an online tutorial on C++ class members. – Tim Randall Feb 15 '19 at 19:35

1 Answers1

1

Your enemy class needs to have the x and y coordinates as member variables. This is how you get each actual enemy to have its own coordinates separate from all the others. The following code should get you up and running, at least. You will presumably want to add a public function to print the coordinates, or to draw the enemy onscreen.

class enemy
{
    int mx, my; // coordinates of this enemy
public:
    enemy(int x, int y)
        : mx(x), my(y) // initialize the coordinates
    {
        // possibly add future initialization here
    }
    void mov()
    {
        ++mx;
        --my;
    }
}

Then you can create and move two enemies as before:

enemy test_one(x,y);
test_one.mov();

enemy test_two(x2,y2);
test_two.mov();

Note that x,y,x2,y2 are no longer variables storing the current positions of the enemies, but constants defining their start positions.

Tim Randall
  • 4,040
  • 1
  • 17
  • 39