我正在为我正在编写的 GBA 游戏进行一些碰撞检测和处理,并且在将处理部分放入函数时遇到了问题。我正在尝试更改成员变量的值(在本例中Player.global_x
),但是将对象传递给函数不允许这样做。相关代码如下:
主文件
bool CheckCollision(sprite obj1, sprite obj2){
int obj1_top = obj1.global_y;
int obj1_bottom = obj1.global_y + (obj1.height-1);
int obj1_left = obj1.global_x;
int obj1_right = obj1.global_x + (obj1.width-1);
int obj2_top = obj2.global_y;
int obj2_bottom = obj2.global_y + (obj2.height-1);
int obj2_left = obj2.global_x;
int obj2_right = obj2.global_x + (obj2.width-1);
if(obj1_right < obj2_left){ // if obj1 is left of obj2
return false;
}
if(obj1_left > obj2_right){ // if obj1 is right of obj2
return false;
}
if(obj1_bottom < obj2_top){ // if obj1 is above obj2
return false;
}
if(obj1_top > obj2_bottom){ // if obj1 is below obj2
return false;
}
return true;
}
void HandleCollision(sprite obj1, sprite obj2){
if(obj1.direction == RIGHT){
Player.global_x -= (obj1.global_x + obj1.width) - obj2.global_x; // This works but is not modular
obj1.global_x -= (obj1.global_x + obj1.width) - obj2.global_x; // This does not work
}
}
void CheckAllPossibleCollisions(){
bool collision = false;
for(int i=0; i<(WallsVector.size()); i++){
collision = CheckCollision(Player, WallsVector.at(i));
if(collision==true){
// This piece of code works, but would incur repetition of code for each different type of game object
/*if(Player.direction == RIGHT){
Player.global_x -= ((Player.global_x+Player.width) - WallsVector.at(i).global_x);
}*/
HandleCollision(Player, WallsVector.at(i));
}
}
}
该函数在传递对象时工作正常,但在更改变量时CheckCollision()
不起作用。HandleCollision()
您可以提出任何意见来帮助解决这个问题,我们将不胜感激,谢谢!