Angelinasen,
не плодите темы
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
html{
height: 100%;
}
body.gradient{
background-image:radial-gradient(red,yellow);
background-repeat: no-repeat;
background-size: 100% 100%;
}
.image{
--color: #FF0000;
width: 50px;
height: 50px;
background-image: linear-gradient(to right, var(--color), black);
}
.image:nth-child(2){
--color: #008000;
width: 10px;
height: 10px;
}
</style>
</head>
<body>
<div class="image" ></div>
<div class="image" ></div>
<script>
const pressedKeys = new Set();
addEventListener("keydown", event => {
pressedKeys.add(event.code);
});
addEventListener("keyup", event => {
pressedKeys.delete(event.code);
});
let dt, lastT = performance.now();
const image = document.querySelectorAll(".image");
const userKeys = [
[
["KeyW", -.1],
["KeyS", .1],
["KeyD", .1],
["KeyA", -.1]
],
[
["ArrowUp", -.1],
["ArrowDown", .1],
["ArrowRight", .1],
["ArrowLeft", -.1]
]
]
const users = userKeys.map((keys, i) => ({
matrix : new DOMMatrix([1, 0, 0, 1, 100 + 100 * i, 100 + 100 * i]),
user: image[i],
keys
}));
const checkCollision = users => {
const [{user : one}, {user : two}] = users;
let {top : a, left : c} = one.getBoundingClientRect();
let {top : b, left : d} = two.getBoundingClientRect();
a -= b;
c -= d;
return a >= -50 && a <= 10 && c >= -50 && c <= 10
}
(function loop(t) {
dt = t - lastT;
lastT = t;
users.forEach(({matrix, user, keys}) => {
keys.forEach(([key, delta], i) => {
let vector = i < 2 ? [0, delta * dt] : [delta * dt, 0];
if (pressedKeys.has(key)) matrix.translateSelf(...vector);
})
user.style.transform = matrix;
})
document.body.classList.toggle('gradient', checkCollision(users));
requestAnimationFrame(loop);
})(lastT);
</script>
</body>
</html>