2

I'm making a game where a player has to navigate a map and get to an end goal. I've got the player moving and the end goal working; however after I've drawn the walls the player can still move through them.

My question is, how can I stop the player from moving through the walls?

Hoxephos
  • 71
  • 1
  • 1
  • 6
  • 1
    Read up on [collision detection.](http://gamedev.stackexchange.com/questions/18261/how-can-i-implement-fast-accurate-2d-collision-detection) Plenty of resources online. – Mike Cluck Nov 16 '16 at 21:24
  • Possible duplicate of [Javascript: Collision detection](http://stackoverflow.com/questions/2440377/javascript-collision-detection) – Mike Cluck Nov 16 '16 at 21:24
  • 2
    Before you move the player, you have to check if there is a wall there. If there is a wall, don't move the player there. – Fredrik Lundvall Nov 16 '16 at 21:26

2 Answers2

1

Assuming your character and the wall is represented by an axis-aligned bounding box, or AABB, the solution is very simple:

function isColliding(pos11, pos12, pos21, pos22){
    return (
        (pos11.x < pos21.x && pos21.x < pos12.x &&
        pos11.y < pos21.y && pos21.y < pos12.y) ||
        (pos11.x < pos22.x && < pos22.x < pos12.x &&
        pos11.y < pos22.y && pos22.y < pos12.y)
    );
}

// Call like this
isColliding(playerUpperAabbCorner, playerLowerAabbCorner, wallUpperAabbCorner, wallLowerAabbCorner);

This checks if any corners overlap each other, which would indicate a collision. All corners are 2-dimensional coordinates, which hold properties .x and .y.

0

HTML Canvas doesn't have a collision detector sistem. So, you must describes the walls in JavaScript so you draw them from this description. Next, you have to process the position every time the player moves.

I.e.

wall = []
wall[0] = {"p1":[0,0],"p2":[0,100]} // the P1 and P2 points of line of wall
...

After, you must determine players corners. For each corner, you may detect if is in wall.

function line_detect(wall,point){ // based on line formula of analytic geometry
    var a = (wall.p1[0] - wall.p2[0]) / (wall.p1[1] - wall.p2[1]);
    var b = wall.p1[1];
    var y = a*point[0]+b;
    if(y == point[1])
        return 0;
    else if(y > point[1])
        return 1;
    else return -1;
}

function range_detect(wall,point){
    if(point[0] > wall.p1[0]
    && point[0] > wall.p2[0])
        return 0;
    if(point[0] < wall.p1[0]
    && point[0] < wall.p2[0])
        return 0;
    if(point[1] > wall.p1[1]
    && point[1] > wall.p2[1])
        return 0;
    if(point[1] < wall.p1[1]
    && point[1] > wall.p2[1])
        return 0;
    return 1;
}

With this functions you can determine if a point is: * after line or before line * in line limits or out line limits

Now, you must have to check for each corner, and if all out of range, so no colision is detect. Is is in the range and all in the same side, no collision is detect too. But if some corners are after line and another before, you have a colision.