I am learning javascript and making a snake game. I am stuck with rotation. The rotation happens on the whole snake element which is the exact thing I am doing and it looks very bad and I am lost of ideas that makes the animation look good.
code:
let direction = 'right';
let snakearray = [1,2,3];
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return;
}
switch (event.key) {
case "ArrowDown":
if(direction === 'up')
{
return;
}
direction = 'down'
rotateSnake(direction);
break;
case "ArrowUp":
if(direction === 'down')
{
return;
}
direction = 'up'
rotateSnake(direction);
break;
case "ArrowLeft":
if(direction === 'right')
{
return;
}
direction = 'left';
rotateSnake(direction);
break;
case "ArrowRight":
if(direction === 'left')
{
return;
}
direction = 'right'
rotateSnake(direction);
break;
default:
return;
}
event.preventDefault();
}, true);
move = function (direction, distance) {
let topOrleft = direction == 'left' || direction == 'right' ? 'left' : 'top';
let snake = document.getElementById('snake');
if (direction == 'left' || direction == 'up') {
distance *= -1;
}
let snakeBoundingRect = snake.getBoundingClientRect();
let snakeCurrentCoordinates = direction === 'left' || direction === 'right' ? snakeBoundingRect.left : snakeBoundingRect.top;
snake.style[topOrleft] = (snakeCurrentCoordinates + distance) + 'px';
}
drawSnake = function()
{
for (let index = 0; index < snakearray.length; index++) {
let span = document.createElement('span');
let snake = document.getElementById('snake');
span.style.left = 0 + (index * -16) + 'px';
span.style.top = '0px';
span.classList.add('square');
span.id = 'id-' + (index + 1);
snake.appendChild(span);
snake.style.position = 'absolute';
}
}
rotateSnake = function(direction)
{
let snake = document.getElementById('snake');
let snakenodes = document.getElementById('snake').childNodes;
console.log(snakenodes);
let rotation = null;
switch(direction)
{
case 'down':
rotation = 'rotate(90deg)';
break;
case 'up':
rotation = 'rotate(270deg)';
break;
case 'left':
rotation = 'rotate(180deg)';
break;
case 'right':
rotation = 'rotate(0deg)';
break;
}
snake.style.transform = rotation;
}
drawSnake();
let moveInterval = setInterval(() => move(direction, 5), 1000 / 5);
<!DOCTYPE html>
<html>
<head>
<title>Snake Movements</title>
<style>
.square {
position: absolute;
height: 15px;
width: 15px;
background-color: blue;
}
</style>
</head>
<body>
<span id="snake"></span>
</body>
</html>
help me with the rotation of the snake with code explanation, thank you.