Javascript Canvas Game - Collision Detection

Lewis

I'm building a little mini tile engine game. I'm currently working on implementing simple block based collision detection, however I'm having real problems. I've googled this for hours looking at different implementations but can't seem to get my head around it. My current effort (only currently detecting collisions when the player moves right), mostly works but allows the player to pass through the bottom part of the obstacle. The collision uses the normal map array to detect collisions, any value of 2 in the map is a solid object.

I understand the concepts of what I need to do - before I move my player, calculate what cell the player will end up in. Check what value has been assigned to that cell. If it is 2, don't allow the player to move.

My issue is figuring out what cell the player will end up in as technically, at points, the player can be in 4 cells at the same time. I've tried using origins and 4 corner detection to get around this, but I just can't get it working.

JS Fiddle HERE - https://jsfiddle.net/j1xqxze8/

My Code;

    var Player = function() {
        this.width = 16;
        this.height = 16;
        this.position   = {};
        this.position.x = 32;
        this.position.y = 32;
        this.speed      = 8;

        this.render = function() {
            window.context.fillStyle = 'white';
            window.context.fillRect(this.position.x, this.position.y, this.width, this.height);
        };

        var _self = this;

        this.didCollide = function(dir) {
            if(dir == 'right'){
                var newBlock = window.tileMap.getCell(Math.floor((_self.position.x + _self.width) / 32), Math.floor((this.position.y + this.height / 2) / 32));

                if(newBlock == 2)
                    return true;
            }
        };

        window.addEventListener('keydown', function(e) {
            if(e.keyCode == 38 || e.keyCode == 87){
                _self.position.y -= _self.speed;
            }

            if(e.keyCode == 40 || e.keyCode == 83){
                _self.position.y += _self.speed;
            }

            if(e.keyCode == 37 || e.keyCode == 65){
                _self.position.x -= _self.speed;
            }

            if(e.keyCode == 39 || e.keyCode == 68){
                if(!_self.didCollide('right')){
                    _self.position.x += _self.speed;
                }
            }
        })
    };

var TileMap = function() {
    this.map = [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
    ];

    this.tileSize = 32;
    this.colors = ['black', 'red', 'green'];

    this.getCell = function(x, y){
      return this.map[y][x];
    };

        this.render = function(){
            for(var x = 0; x < this.map.length; x++){
                for(var y = 0; y < this.map.length; y++){
                    // SWAP Y AND X IN THE FILLSTYLE DUE TO BACKWARDS/MIRRORED JS ARRAY READING
                    window.context.fillStyle = this.colors[this.map[y][x]];
                    window.context.fillRect((x * this.tileSize) - window.camera.position.x, (y * this.tileSize) - window.camera.position.y, this.tileSize, this.tileSize);

                    window.context.strokeStyle = 'yellow';
                    window.context.strokeRect((x * this.tileSize) - window.camera.position.x, (y * this.tileSize) - window.camera.position.y, this.tileSize, this.tileSize);
                }
            }
        }
    };
markE

Since you are moving the player 8 positions per keydown, in keydown you must test each of those 8 interim positions to see if a collision occurs.

Warning: untested code -- some tweaking (probably!) required

window.addEventListener('keydown', function(e) {
    // save x,y before the move
    var beginningX=_self.position.x;
    var beginningY=_self.position.y;

    // test each interim positon between the beginning & 
    // current position for collisions
    // if a collision occurs, stop at the collision position
    if(e.keyCode == 38 || e.keyCode == 87){
        _self.position.y -= _self.speed;
        _self.position.y = testInterimVerticalCollisions(
            beginningY, _self.position.y, _self.position.x);
    }

    if(e.keyCode == 40 || e.keyCode == 83){
        _self.position.y += _self.speed;
        _self.position.y = testInterimVerticalCollisions(
            beginningY, _self.position.y, _self.position.x);
    }

    if(e.keyCode == 37 || e.keyCode == 65){
        _self.position.x -= _self.speed;
        _self.position.x = testInterimHorizontalCollisions(
            beginningX, _self.position.x, _self.position.y);
    }

    if(e.keyCode == 39 || e.keyCode == 68){
        _self.position.x += _self.speed;
        _self.position.x = testInterimHorizontalCollisions(
            beginningX, _self.position.x, _self.position.y);
        }
    }
})

// test if any interim movement caused a collision
// if yes, return the x that caused the collision
// if no, return the ending x
function testInterimHorizontalCollisions(beginningX,endingX,y){
    for(var x=beginningX;x<=endingX;x++){
        // TODO: adjust for camera position offset
        var cellX = parseInt(x/cellWidth);
        var cellY = parseInt(y/cellHeight);
        if(getCell(cellX,cellY)==2){return(x);}
    }
    return(endingX);
}

// test if any interim movement caused a collision
// if yes, return the y that caused the collision
// if no, return the ending y
function testInterimVerticalCollisions(beginningY,endingY,x){
    for(var y=beginningY;y<=endingY;y++){
        // TODO: adjust for camera position offset
        var cellX = parseInt(x/cellWidth);
        var cellY = parseInt(y/cellHeight);
        if(getCell(cellX,cellY)==2){return(y);}
    }
    return(endingY);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Collision detection in javascript canvas tanks game

From Dev

Collision detection in javascript game

From Dev

Problem with collision detection is JS canvas game

From Dev

JavaScript canvas: "Random" errors with collision detection

From Dev

HTML Canvas game: 2D collision detection

From Dev

if statement in JavaScript game not working as desired to allow for collision detection

From Dev

Collision Detection with javascript on the html canvas element without using jquery

From Dev

Collision detection of 2 gifs on canvas

From Dev

Optimization of JavaScript collision detection

From Dev

Collision detection in java 2d game

From Dev

Java Game Physics - Determine intersection and collision detection

From Dev

Trying to use quadtrees for collision detection in a game

From Dev

Game score via collision detection increment

From Dev

Trying to use quadtrees for collision detection in a game

From Dev

Collision Detection for fast moving game object in Unity

From Dev

Collision detection in html5 canvas

From Dev

How to change canvas fillStyle with collision detection?

From Dev

Shape detection javascript canvas

From Dev

Javascript Canvas edge detection

From Dev

Javascript Canvas edge detection

From Dev

JavaScript canvas game development

From Dev

JavaScript canvas game development

From Dev

game viewport focus vs collision detection on y axis against gravity

From Dev

Collision detection in 2D game without tiles XNA

From Dev

Collision Detection in FPS Game using three.js

From Dev

Phonegap game development collision detection regarding different screen sizes

From Dev

Collision detection in 2D game without tiles XNA

From Dev

game viewport focus vs collision detection on y axis against gravity

From Dev

Collision Detection in FPS Game using three.js

Related Related

  1. 1

    Collision detection in javascript canvas tanks game

  2. 2

    Collision detection in javascript game

  3. 3

    Problem with collision detection is JS canvas game

  4. 4

    JavaScript canvas: "Random" errors with collision detection

  5. 5

    HTML Canvas game: 2D collision detection

  6. 6

    if statement in JavaScript game not working as desired to allow for collision detection

  7. 7

    Collision Detection with javascript on the html canvas element without using jquery

  8. 8

    Collision detection of 2 gifs on canvas

  9. 9

    Optimization of JavaScript collision detection

  10. 10

    Collision detection in java 2d game

  11. 11

    Java Game Physics - Determine intersection and collision detection

  12. 12

    Trying to use quadtrees for collision detection in a game

  13. 13

    Game score via collision detection increment

  14. 14

    Trying to use quadtrees for collision detection in a game

  15. 15

    Collision Detection for fast moving game object in Unity

  16. 16

    Collision detection in html5 canvas

  17. 17

    How to change canvas fillStyle with collision detection?

  18. 18

    Shape detection javascript canvas

  19. 19

    Javascript Canvas edge detection

  20. 20

    Javascript Canvas edge detection

  21. 21

    JavaScript canvas game development

  22. 22

    JavaScript canvas game development

  23. 23

    game viewport focus vs collision detection on y axis against gravity

  24. 24

    Collision detection in 2D game without tiles XNA

  25. 25

    Collision Detection in FPS Game using three.js

  26. 26

    Phonegap game development collision detection regarding different screen sizes

  27. 27

    Collision detection in 2D game without tiles XNA

  28. 28

    game viewport focus vs collision detection on y axis against gravity

  29. 29

    Collision Detection in FPS Game using three.js

HotTag

Archive