how to make the hedge move towards the cursor arrow

Asked

Viewed 23 times

0

Next I wanted to do something like this hedge animation, however I do not know how to make the cover follow the mouse, the method I used at most with low-up or right-left. The code below ta inside setInterval, and if I configure for the keyboard works the drive only the mouse that will not.

 const px = 15;
let snake = [];
snake[0] = {
    x: 5 * px,
    y: 3 * px
}

let direction;


export default function snakeAnimation() {

    const canvas = document.querySelector('.screen');
    const ctx = canvas.getContext('2d');
    const px = 15;

    canvas.width = 30 * 15;
    canvas.height = 30 * 15;


    ctx.fillStyle = "rgb(2550,255,255)";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

        if (snake[0].y < 0 && direction == 'ArrowUp') {
        console.log('fire', snake[0].y)
        snake[0].y = canvas.width;
        console.log('fire', snake[0].y)
    }

    if (snake[0].x >= canvas.width && direction == 'ArrowRight') {
        snake[0].x = 0
    }

    if (snake[0].y >= canvas.height && direction == 'ArrowDown') {
        snake[0].y = 0;
    }

    if (snake[0].x < 0 && direction == 'ArrowLeft') {
        snake[0].x = canvas.width;
    }



    let trasparent = 5;


    for (let i = 0; i < snake.length; i++) {

        if(i == 0){
            ctx.fillStyle = `#fc5c65`;
            ctx.fillRect(snake[i].x, snake[i].y, px, px);
        }else{
            ctx.fillStyle = `rgba(255,0,0,0.${trasparent})`;
            ctx.fillRect(snake[i].x, snake[i].y, px, px);
            trasparent = trasparent - 1;
        }
        
  
    }

    let snakeX = snake[0].x;
    let snakeY = snake[0].y;



    if (direction == 'ArrowUp') snakeY -= px;
    if (direction == 'ArrowRight') snakeX += px;
    if (direction == 'ArrowDown') snakeY += px;
    if (direction == 'ArrowLeft') snakeX -= px;



     

    const sheadSnake = {
        x: snakeX,
        y: snakeY
    }

    canvas.addEventListener('mousemove', update);
    function update(e){
        let x = Math.round(e.clientX - canvas.offsetLeft);
        let y = e.clientY - canvas.offsetTop;
    

        // movimento
        if(x < (snakeX + px) && snakeY){
            direction = 'ArrowLeft';

        }

        if(x > (snakeX + px)){
            direction = 'ArrowRight';

        }

        if(y < (snakeY + px)){
            direction = 'ArrowUp';

        }

        if(y > (snakeY + px)){
            direction = 'ArrowDown';

        }

        console.log(x, y)
    }


    snake.unshift(sheadSnake);
    console.log(snakeX)





}
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.