Need help with JavaScript stuff
So basically I can't make collisions happen with objects in an array and I've been trying for hours.
I can't share the code, but I can add you to the project if you can help
So basically I can't make collisions happen with objects in an array and I've been trying for hours.
I can't share the code, but I can add you to the project if you can help
Okay there are tons of JavaScript collision detections on microStudio? But here this is the translated code of the Barriers tutorial by me in microScript to JavaScript for the best collision detection possible for 2d flat games:
init = function() {
player = {
x: -50,
y: 0,
speed: 2,
radius: 6
};
barriers = [];
barriers.push({ x: 0, y: 0, w: 30, h: 30 });
};
resolveBarrierCollision = function() {
for (let i = 0; i < barriers.length; i++) {
let b = barriers[i];
// Find the closest point on the rectangle to the circle's center
// microStudio rectangles are positioned by their centers
let closestX = Math.max(b.x - b.w / 2, Math.min(player.x, b.x + b.w / 2));
let hisY = Math.max(b.y - b.h / 2, Math.min(player.y, b.y + b.h / 2));
// Calculate distance between circle center and this closest point
let distanceX = player.x - closestX;
let distanceY = player.y - hisY;
let distanceSquared = (distanceX * distanceX) + (distanceY * distanceY);
// If the distance is less than the circle's radius, an intersection occurs
if (distanceSquared < player.radius * player.radius) {
let distance = Math.sqrt(distanceSquared);
// Prevent division by zero if player is exactly at the intersection point
if (distance === 0) continue;
// Distance needed to push the player completely out
let overlap = player.radius - distance;
// Push the player away from the closest point along the collision vector
player.x += (distanceX / distance) * overlap;
player.y += (distanceY / distance) * overlap;
}
}
};
update = function() {
if (keyboard.LEFT) player.x -= player.speed;
if (keyboard.RIGHT) player.x += player.speed;
if (keyboard.UP) player.y += player.speed;
if (keyboard.DOWN) player.y -= player.speed;
resolveBarrierCollision();
};
draw = function() {
screen.clear("#0A0E1A");
for (let i = 0; i < barriers.length; i++) {
let b = barriers[i];
screen.fillRect(b.x, b.y, b.w, b.h, "#404858");
}
// microStudio fillRound uses center coordinates, diameter width, and diameter height
screen.fillRound(player.x, player.y, player.radius * 2, player.radius * 2, "#A5D6A7");
screen.drawText("YOU", player.x, player.y + 14, 6, "#A5D6A7");
screen.drawText("Arrow keys to move. Try walking into the block.", 0, -80, 6, "#888888");
};
If it is something different then sorry let me know.
I'm crine. I literally wrote heigth instead of height and that's why it didn't work lolðŸ˜