我使用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)移动,其他的不是因为它们有不同的方式来调用位置的变量。我怎样才能解决这个问题?
你的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
不再是存储敌人当前位置的变量,而是定义其起始位置的常数。