Note that there are some explanatory texts on larger screens.

plurals
  1. POCollision detection in HTML5 canvas. Optimization too
    text
    copied!<p>I am making a platform game, but i have a problem with my collision detection. I've made a function that draws a tile on the screen/map. In that function is my collision detection, it works fine when only one tile is drawn, but when i created "stairs" with three tiles, the first tile doesnt work propertly. The player is just being "pushed" up on the tile. The side detection isn't working. And the other tiles are working just fine.</p> <p>Here is the code for collision detection and tile drawing:</p> <pre><code>//Function that allows you to draw a tile function drawTile(type, x, y, collision){ var tileImg = new Image(); tileImg.onload = function(){ ctx.drawImage(tileImg, x, y) }; tileImg.src = "images/" + type + ".png"; if (collision){ //Worst collision detection ever. if((player_x + player_width == x) &amp;&amp; (player_y + player_height &gt; y)){ canMoveRight = false; }else if((player_x == x + 32) &amp;&amp; (player_y + player_height &gt; y)){ canMoveLeft = false; }else if((player_y + player_height &gt; y) &amp;&amp; (player_x + player_width &gt;= x) &amp;&amp; (player_x + player_width &lt;= x + 64)){ player_y = y - player_height; }else{ canMoveRight = true; canMoveLeft = true; } } } //Draw the map function drawMap(){ drawTile("block", 96, 208, true); drawTile("block", 128, 208, true); drawTile("block", 128, 176, true); }; </code></pre> <p>As you can see, the collision detection code kinda sucks. So it also would be good if you showed me better ways of making it.</p> <p>Just say if you need to know something. :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload