# Collision detection not working properly

**URL:** <https://forum.kirupa.com/t/collision-detection-not-working-properly/288643>\
**Category:** programming\
**Created:** [May 19, 2009, 10:22am UTC](https://forum.kirupa.com/t/collision-detection-not-working-properly/288643 "2009-05-19T10:22:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Skribble](https://avatars.discourse-cdn.com/v4/letter/s/b487fb/32.png) [@Skribble](https://forum.kirupa.com/u/Skribble)\
**Post date:** [May 19, 2009, 10:22am UTC](https://forum.kirupa.com/t/collision-detection-not-working-properly/288643/1 "2009-05-19T10:22:42Z")

</div>

Ok so I’m trying to make my hero stop when he hits the walls of the ground MC, named “g”. So I wrote this up:

```auto

if (Key.isDown(Left)) {
      if (!g.hitTest(this._x-(hXbuff+xSpeed), this._y-20, true) ) {
           dir = "left";
           this._x -= xSpeed;
      }else{
           heroStatus = "stand";
      }
}else if (Key.isDown(Right)) {
      if (!g.hitTest(this._x+(hXbuff+xSpeed), this._y-20, true) ) {
           dir = "right";
           this._x += xSpeed;
      }else{
           heroStatus = "stand";
      }
} else {
      heroStatus = "stand";
}

```

It tests for the heros X, plus hXbuff which is equal to 20, and xSpeed which is equal to 7. If the heros X, plus these variables, is not hitting a wall, then the hero may move, otherwise the hero goes back to standing; this prevents the running animation being played when hitting a wall.

This works, but the problem is that it doesn’t work all the time. Randomly you will be able to move to a closer position between the heros X and where it is meant to have stopped; hXbuff+xSpeed. (pictured below)  
\*\*  
NOTE: This is what is meant to happen. The green lines indicate hXbuff+xSpeed.\*\*  
 ![](http://img217.imageshack.us/img217/5361/yesv.jpg)

\*\*NOTE: This is what should NOT be happening. \*\*  
 ![](http://img217.imageshack.us/img217/990/27776207.jpg)

Is there any reason the code above would cause this to happen? It looks fine to me. Or can you think of any _other_ reason this would be happening?

Thanks!
