Developers Planet

musse1 February 2016

Player facing away from the wall should not collide

I'm working on my first Javascript game. It is a top down 2D view (think GTA 1/2). Now I'm having trouble with collision detection. I have multiple entities where one is the player and the other is a static object (let's say a wall for simplicity).

Each object has X/Y coordinates and the player also has a velocity and an angle (which way the player is facing from 0-360 degrees). The collision detection against the wall works fine and I stop velocity on one of the axis if the player collide having as result the player can "slide" agains the wall.

Now to the issue: Once the player collides agains the wall the movement on one of the axis is stopped. If the player after that turns around and facing away from the wall the movement of that axis is still stopped since ha collided.

I would like the player, if facing away from the object, is free to move how he want's how do I achieve this? I guess I need to figure out which way the player is facing and if he is facing against or away from the object?

``````for( var i = 0; i < GAME.entities.length; i++ ) {
if( this._collision( GAME.entities[i] ) ) {

var distanceX = GAME.entities[i].x - this.x;
var distanceY = GAME.entities[i].y - this.y;

if( distanceX < 0 )
distanceX *= -1;

if( distanceY < 0 )
distanceY *= -1;

if( !stopX ) {
stopX = ( distanceX > distanceY );
}

if( !stopY ) {
stopY = ( distanceX < distanceY );
}
}
}
``````

musse1 February 2016

I figured out how to do this:

``````var degrees = ( Math.atan2( GAME.entities[i].x - this.x, GAME.entities[i].y - this.y ) * 180 / Math.PI ) + this.angle
``````