Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
How to check if a drawn wall is touching player (canvas) for collisions?

I have a 2D map using canvas html element and I have drawn a red square as a player, and a wall out of light blue beneath it. I want to know how I can detect if the player (red square) is touching the wall (light blue). I do not have classes or anything, just drawn squares using the canvas element, with set positions.

CODE:

var ctx = document.getElementById("canvas").getContext('2d')
document.getElementById("canvas").tabIndex = 1;
// quick way to get focus so keypresses register
ctx.font = '8px sans';
var offsetx = 0
var offsety = 0
var things = [
    [0,100,300,50]
]

function offset() {
    ctx.save();
    ctx.translate(offsetx,offsety);
    // clear the viewport
    ctx.clearRect(-offsetx, -offsety, 300,300);
    ctx.fillStyle = "red";
    ctx.fillRect(50-offsetx,50-offsety,8,8)
    // draw the other stuff on the screen, which have the set positions in the array.
    var l = things.length;
    var i = 0;
    for (i = i; i < l; i++) {
        var x = things[i][0];
        var y = things[i][1];

        var sizex = things[i][2]
        var sizey = things[i][3]
        ctx.fillStyle = 'lightblue';
        ctx.fillRect(x, y, sizex, sizey);
        ctx.fillStyle = 'black';
    }
    ctx.restore();
}
offset(); // the first call to draw all the elements.

document.getElementById("canvas").addEventListener('keydown', function(e) {
    if (e.keyCode === 37) { // left
        offsetx++;
    } else if (e.keyCode === 39) { // right
        offsetx--;
    } else if (e.keyCode === 38) { // up
        offsety++;
    } else if (e.keyCode === 40) { // down
        offsety--;
    }
    offset();
}, false);

setInterval(function() {
    // in here i would check for the collisions
}, 10);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I figured it out on my own, since noone else would. Basically you give the drawn walls, (with set posisiton) some set positions for where the resistance or collision point should be. then, before the player is move, in the move function you check to see if that player is on, right before, or in that wall. if so, return, otherwise continue. here is my code example:

jsfiddle.net/57xm0fw1/1/

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!