+ 2

Am trying to code snake movement, in my code, it's moving but it's length is increasing, not remaining constant

var brd = document.getElementById("can"); var ctx = brd.getContext("2d"); ctx.width = 600; ctx.height = 600; var box =10; let snake = []; snake[0]={x:5*box, y:6*box}; snake[1]={x:4*box, y:6*box}; snake[2]={x:3*box, y:6*box}; function drawS() { for(let i=0;i<snake.length;i++){ ctx.fillStyle = (i==0)?"green":"red"; ctx.fillRect(snake[i].x,snake[i].y,box,box) } var snakeX = snake[0].x; var snakeY = snake[0].y; snake.pop(); var NewHead = {x:snakeX,y:snakeY+box}; snake.unshift(NewHead); } let draw = setInterval(drawS,100); // snake is array of box, Am using, snake.pop method to remove last tail peace , and snake.unshift () to add new box on head, But, it's size is increasing, I want it's size to be constant.

13th May 2020, 11:58 AM
ASHISH PANDEY
ASHISH PANDEY - avatar
2 odpowiedzi
+ 2
Everything is fine just clean the canvas everytime in the loop before drawing the snake The trail is just there because of previous render // Have a ref to canvas elememt ctx.fillStyle = "#000"; // put your by color ctx.fillRect(0,0, canvas.width , canvas.height); Put it in drawS() function at top
16th May 2020, 9:32 PM
goodbits
goodbits - avatar
0
A lot thanx, I was stuck, 🙏🏽🙏🏽
21st May 2020, 4:21 PM
ASHISH PANDEY
ASHISH PANDEY - avatar