Currently I am designing a 2d platformer and I have implemented collision detection where my code is as follows:
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...
Which all seems to work well however when colliding with an object horizontally, if I keep holding down the right key and press the up key, the function recognizes the object is still colliding, then applies the same force which would be applied if the object in-game had jumped and collided above, so the in-game object gets pushed down even though there is no up force.
I have tried implementing separate boolean values for collision in the X and Y however this has not affected the outcome.
The only fix I have found is if when processing the keys, I use else if's instead of if's. However this makes for very linear movement and the object cannot move diagonally.
Any suggestions?