Почему змея оставляет остатки на холсте и почему они падают на первый объект?Я хотел, чтобы объект двигался, чтобы скопировать положение объекта перед ним.Извините, если за моим кодом трудно следовать, я уверен, что проблема в функции update (), и я некоторое время размышлял и не могу понять.Я думаю, что первый ход правильный, но после того, как они просто сталкиваются.
const c = document.querySelector("canvas");
const ctx = c.getContext("2d");
const width = (c.width = 800);
const height = (c.height = 400);
var length = 4;
var parts = new Array();
class SnakePart {
constructor() {
this.x = width / 2;
this.y = height / 2;
this.isFirst = 1;
this.direction = 39;
this.id = 0
}
show() {
ctx.beginPath();
ctx.arc(this.x, this.y, 5, 0, 2 * Math.PI);
ctx.stroke();
}
update(other) {
if (this.isFirst == 1) {
if (this.direction == 37)
this.x -= 10;
if (this.direction == 39)
this.x += 10;
if (this.direction == 38)
this.y -= 10;
if (this.direction == 40)
this.y += 10;
} else if (this.isFirst == 0) {
this.other = other;
this.x = this.other.x;
this.y = this.other.y;
}
}
}
for (var i = 0; i < length; i++) {
let snakePart = new SnakePart();
parts.push(snakePart);
if (i > 0) {
parts[i].x = parts[i - 1].x - 10;
parts[i].isFirst = 0;
}
parts[i].id = i;
parts[i].show();
}
setInterval(function() {
ctx.clearRect(parts[length - 1].x - 5, parts[length - 1].y - 5, 10, 10);
for (var i = 0; i < length; i++) {
if (parts[i].isFirst == 1) {
parts[i].update();
}
if (parts[i].isFirst == 0) {
parts[i].update(parts[i - 1]);
}
parts[i].show();
}
}, 1000);
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id="canvas" width="800" height="400" style="border:1px solid #000000;">
</canvas>
<script src="snake.js"></script>
<button onclick="parts[0].direction = 38">UP</button>
<button onclick="parts[0].direction = 39">RIGHT</button>
<button onclick="parts[0].direction = 40">DOWN</button>
<button onclick="parts[0].direction = 37">LEFT</button>
</body>
</html>