jhon k.
jhon k.

Reputation: 1

Sprite coordinates issue

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?

Upvotes: -1

Views: 42

Answers (1)

Tim Randall
Tim Randall

Reputation: 4145

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.

Upvotes: 1

Related Questions