Ask coding questions

← Back to all posts
collision problems
md18096e (1)

repl: https://replit.com/@md18096e/game1#script.js

I made collision detection for objects and players inside of my game but there is a problem; when I collide with a object on the top, I move left when I collide. This is a similar thing that happens with other sides. I tried to fix it by making it that if it detect a collision, it will reverse the speed of x and the speed of y. It worked well until I found a glitch that if I move backwards at a certain time, I will glitch through the entire object. I deleted the original one I used, Currently I removed the code making the speed reverse and restored it to a copy and pasted one from w3schools.com in https://www.w3schools.com/graphics/tryit.asp?filename=trygame_obstacle_hit. I modified the code to detect a collision:

if ((mybottom < othertop) ||
      (mytop > otherbottom) ||
      (myright < otherleft) ||
      (myleft > otherright)) {
      } else {
        if(mybottom >= othertop) {
          playerSt.dy = -1;
        }
        if(mytop <= otherbottom) {
          playerSt.dy = 1;
        }
        if(myright >= otherleft) {
          playerSt.dx = 1;
        }
        if(myleft <= otherright) {
          playerSt.dx = -1;
        }
      }

I've been stuck on this same thing for a month.

Answered by GameDev46 (204) [earned 5 cycles]
View Answer
Comments
hotnewtop
GameDev46 (204)

For collision detection you would want to check if all of those where true as right now the collision script would fire if you moved above or beneath the object, even if you weren’t touching it. I would always say if players y is greater than the objects bottom and less than the objects top and if that was true you would then check if the players x was more than the left of the object and less than the right and if so then the player would’ve collided with the object and if so get there speed and reverse them (times by -1)