Check out this CodePen demo where you can control the movement of the "player" square using arrow keys. You can also place a light by pressing the spacebar and the player is supposed to be prevented from crossing over the blue lines by getting pushed in the opposite direction. The movement of the "player" is controlled by x and y velocity variables, which are multiplied by -1 (plus some value) if a collision is detected. However, there seems to be an issue where the player gets stuck in a position where they can only move backward from the wall, appearing to be stuck on a perpendicular axis. For instance, if the wall is above the player, they can only move downwards and not left or right after hitting the wall. I am looking to implement a smooth sliding collision detection mechanism where the player, when stuck at the wall, would slowly slide down the left or right side depending on whether the left or right arrow key is pressed. While I have been able to achieve this to some extent, there is always one direction that flows more smoothly, resulting in the player sliding down in a particular direction. I have considered using rays or other methods to detect hits, but they seem to require more computational time compared to a simple approach. I would appreciate any suggestions or recommendations on how to build a scalable collision detection system.
let xVelocity = 0;
let yVelocity = 0;
var blockedMapGrid = [[0,30],[0,50],[0,100],[0,150],[0,200],[0,250],
[50,0],[100,0],[150,0],[200,0],[250,0],[300,0]];
var animate = function() {
if (keyState[37]) {
xVelocity -= 1;
}
if (keyState[38]) {
yVelocity += 1;
}
if (keyState[39]) {
xVelocity += 1;
}
if (keyState[40]) {
yVelocity -= 1;
}
for (var i = 0; i < blockedMapGrid.length; i++) {
if (Math.abs(player.position.x - blockedMapGrid[i][0]) +
Math.abs(player.position.y - blockedMapGrid[i][1]) < 36) {
xVelocity = -xVelocity * 1.2;
yVelocity = -yVelocity * 1.2;
console.log("Blocked by " + blockedMapGrid[i][0])
};
}
player.position.x = player.position.x + xVelocity;
player.position.y = player.position.y + yVelocity;
yVelocity *= 0.80;
xVelocity *= 0.80;
camera.position.x = player.position.x;
camera.position.y = player.position.y;
requestAnimationFrame(animate);
renderer.render(scene, camera);
};