目前我正在设计一个 2d 平台游戏,我已经实现了碰撞检测,我的代码如下:
if (keys['W']){ checkCollision(vector of bounded boxes, direction; }
if (keys['A']){ checkCollision(vector of bounded boxes, direction; }
ETC...
checkCollision(vector, direction){
for(each boundary box){
if (dir == 'UP'){
if (AABB collision check){hit = true;}
else{hit = false;}
walk(velocity, direction);
}
else if (dir == 'RIGHT'){
if (AABB collision check){hit = true;}
else{hit = false;}
walk(velocity, direction);
}
}
}
ETC...
walk(velocity, direction){
if (dir == 'UP'){
if (hit){ y -= 2; }
else{ y += velocity; }
}
else if (dir == 'RIGHT'){
if (hit){ x -= 2; }
else{ x -= velocity; }
}
ETC...
这一切似乎都很好,但是当与物体水平碰撞时,如果我一直按住右键并按下向上键,该功能会识别出物体仍在碰撞,然后施加相同的力,如果物体在-游戏在上方跳跃并碰撞,因此即使没有向上的力量,游戏中的物体也会被推下。
我尝试在 X 和 Y 中为碰撞实现单独的布尔值,但这并没有影响结果。
我发现的唯一解决方法是,如果在处理密钥时,我使用 else if's 而不是 if's。然而,这会导致非常线性的移动,并且对象不能沿对角线移动。
有什么建议么?