Estoy tratando de construir el juego Snake usando HTML y Javascript, pero tengo este problema:
context.fillStyle = 'red'; context.fillRect( apple.x * BLOCK_SIZE + 1, apple.y * BLOCK_SIZE + 1, BLOCK_SIZE - 1, BLOCK_SIZE - 1 ); context.fillStyle = 'lime'; for(var i = 0; i < snake.body.length; i++) { context.fillRect( snake.body[i].x * BLOCK_SIZE + 1, snake.body[i].y * BLOCK_SIZE + 1, BLOCK_SIZE - 1, BLOCK_SIZE - 1 ); }La roja es mi manzana y la lima es mi serpiente. Cuando mi serpiente toca la manzana, pasa por debajo de ella, por lo que parecerá que mi juego se detiene por un marco. ¿Hay alguna forma de hacer que mi serpiente esté siempre encima de mi manzana?
Si está dibujando en el orden que muestra en su código, la serpiente va encima de la manzana...
La única forma en que la serpiente pasa por debajo de la manzana es si está dibujando esos elementos en un orden diferente, por lo que puedo ver, su código es bueno.
Aquí hay un fragmento de código de muestra:
const BLOCK_SIZE = 12 var apple = {x:9, y:5} var snake = {body: [{x:1, y:1}, {x:1, y:2}, {x:1, y:3}, {x:2, y:3}, {x:2, y:4}, {x:2, y:5}]} var canvas = document.querySelector("canvas") var context = canvas.getContext("2d") function draw() { context.clearRect(0,0, canvas.width, canvas.height); context.fillStyle = 'red'; context.fillRect( apple.x * BLOCK_SIZE+1, apple.y * BLOCK_SIZE+1, BLOCK_SIZE-1, BLOCK_SIZE-1 ); context.fillStyle = 'lime'; for (var i = 0; i < snake.body.length; i++) { context.fillRect( snake.body[i].x * BLOCK_SIZE+1, snake.body[i].y * BLOCK_SIZE+1, BLOCK_SIZE-1, BLOCK_SIZE-1 ); } } function loop() { const last = snake.body.at(-1).x snake.body.push({x:last+1, y:5}) draw() } draw() setInterval(loop, 800); <canvas id="canvas" width="240" height="140"></canvas>