0

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?

genpfault
  • 51,148
  • 11
  • 85
  • 139
Will
  • 79
  • 1
  • 1
  • 10

1 Answers1

0

The problem you are facing is because you tied in the input and collision systems. The input system should only move the player as per key presses. The collision detection/handling system should solely take care of collisions. Once you decouple them things become much cleaner.

// Main loop
while(1) {

   handleInput();
   ...
   handleCollisions();
   ...
}

If you have too many objects in your game you can use spacial partitioning to reduce the number of collision checks that you have to do. Otherwise you don't have to worry about it.

SNce
  • 2,453
  • 1
  • 16
  • 14