我使用allegro4和C ++为一种类型的敌人创建了一个类。在此类中,我有一个使小精灵移动的函数,如下所示:
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
问题在于,当我创建对象时,第一个对象可以根据函数移动(更新变量x和y),其他对象则没有,因为它们调用位置变量的方式不同。我该如何解决?
答案 0 :(得分:1)
您的enemy
类需要具有x
和y
坐标作为成员变量。这样,您便可以使每个实际敌人的坐标都独立于其他所有敌人。以下代码至少应该使您启动并运行。您可能想添加一个公共功能来打印坐标,或在屏幕上绘制敌人。
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;
}
}
然后您可以像以前一样创建和移动两个敌人:
enemy test_one(x,y);
test_one.mov();
enemy test_two(x2,y2);
test_two.mov();
请注意,x,y,x2,y2
不再是存储敌人当前位置的变量,而是定义其起始位置的常量。