Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

501
Visualizações
Collision detection not working as intended (Arrays, Javascript)

Ill start off by saying im not the best at explaining.

I have attached 2 images to help explain with my problem.

The problem is that the 'player' is colliding with the 'square 2' X position, when it is clearly not in range of the Y position. The green line shows where the player is colliding and stopping, (stopping as in if you hit a wall, you would stop). In image 2, below the black line, is the expected outcome, how do I achieve this? (Scroll for code)

enter image description here

enter image description here

Just in case you need to know, the enemy/player is 50x50px, the rectangle is 70x150px

My Code (JS):

    blockX.forEach(blockX => { // left and right collision
    blockY.forEach(blockY => {
        if (enemy.y + enemy.h >= blockY && enemy.y <= blockY + rect.h) {
                if (enemy.x + enemy.w >= blockX) {
                    if (enemy.x <= blockX + enemy.w) {
                        enemy.x = blockX - enemy.w
                    }
                }
                if (enemy.x <= blockX + rect.w + 13) {
                    if (enemy.x + enemy.w >= blockX) {
                        enemy.x = blockX + rect.w + 13
                    }
                } 
        }
    })
})
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

First of all, you can simplify the code by resetting collision.cr at the beginning of the function, and then all you have to do is set it to true once if met condition, no need for any else

Second, you should have a single condition, that checks both x and y coordinates, not two separates (which by the way, in your code the second condition WILL overwrite previous condition's result, because of the else)

const elPlayer = document.getElementById("player");
const enemies = [
  {
    x: 100,
    y: 34,
    w: 100,
    h: 150
  },
  {
    x: 300,
    y: 34,
    w: 100,
    h: 150
  },
  {
    x: 140,
    y: 54,
    w: 100,
    h: 50
  }
];


window.addEventListener("mousemove", e =>
{
  const player = {
    x: e.x,
    y: e.y,
    w: 20,
    h: 20
  }

//colistion detection
  for(let i = 0; i < enemies.length; i++)
  {
    const enemy = enemies[i];
    const collide = (enemy.x < player.x + player.w &&
                    enemy.x + enemy.w > player.x &&
                    enemy.y < player.y + player.h &&
                    enemy.y + enemy.h > player.y)

    elPlayer.classList.toggle("collide", collide);
    if (collide)
      break;
  }

  elPlayer.style.top = player.y + "px";
  elPlayer.style.left = player.x + "px";
});


[...document.querySelectorAll(".enemy")].forEach((enemy, i) =>
{
  enemy.style.left = enemies[i].x + "px";
  enemy.style.top = enemies[i].y + "px";
  enemy.style.width = enemies[i].w + "px";
  enemy.style.height = enemies[i].h + "px";
});
.enemy
{
  position: absolute;
  background-color: pink;
  border: 1px solid black;
}

#player
{
  position: absolute;
  width: 20px;
  height: 20px;
  background-color: green;
  border: 1px solid black;
}


#player.collide
{
  background-color: red;
}
<div class="enemy"></div>
<div class="enemy"></div>
<div class="enemy"></div>

<div id="player"></div>

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda