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)
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
}
}
}
})
})
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>