Using movable character to interact with any button with JS

Viewed 28

rabbitSpriteSheet.png enter image description here

const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');

let buttons;


const spriteWidth = 192/4;
const spriteHeight = 192/4;

let frameX = 0;
let frameY = 0;
let gameFrame = 0;
let staggerFrames = 20;
let y = 0;

let rabbitX = 0;
let rabbitY = 0;
let speed = 6;


const rabbit = new Image();
rabbit.src = 'rabbitSpriteSheet.png';

document.addEventListener("keydown", (e) => {
    switch(e.key){
        case "s":
            frameY = 0;
            rabbitY +=speed;
            break;
        case "w":
            frameY = 1;
            rabbitY -= speed;
            break;
        case "a":
            frameY = 2;
            rabbitX -= speed;
            break;
        case "d":
            frameY = 3;
            rabbitX += speed;
            break;
    }
})

function animate(){
    let CANVAS_WIDTH = canvas.width = window.innerWidth;
    let CANVAS_HEIGHT = canvas.height = window.innerHeight;

    // Cleares the screen
    ctx.clearRect(0,0,CANVAS_WIDTH, CANVAS_HEIGHT);

    let position = Math.floor(gameFrame/staggerFrames) % 4;
    frameX = spriteWidth * position;

    // Draws the rabbit, first four are cut out, second four are where it is placed (This will stretch the image)
    ctx.drawImage(rabbit,frameX,frameY * spriteHeight,spriteWidth,spriteHeight,rabbitX,rabbitY, spriteWidth * 3, spriteHeight * 3);

    gameFrame++;
    // Reccursive call
    requestAnimationFrame(animate);
}

animate();
#canvas1 {
    border: 5px solid black;
    top:50%;
    position: absolute;
    left: 50%;
    transform: translate(-50%,-50%);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>First Project</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <canvas id="canvas1">
    </canvas>
    <button>Hello World</button>
    <button>Hello World 2</button>

    <script src="script.js"></script>
</body>
</html>

Currently I have a character that is moving around my screen using an animation loop through JavaScript. In my project my goal is to use this character as the cursor. The character is also inside of a canvas that has the size of my screen. I want to be able to interact with buttons by pressing either space bar or e if my character is over them. The problem is I don't want to check for each button if the character falls between the x and y boundaries. Is there a method of doing this, or using some sort of library to check if the character overlaps with an element of type button?

1 Answers

const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');

let buttons;


const spriteWidth = 192/4;
const spriteHeight = 192/4;

let frameX = 0;
let frameY = 0;
let gameFrame = 0;
let staggerFrames = 20;
let y = 0;

let rabbitX = 0;
let rabbitY = 0;
let speed = 6;


const rabbit = new Image();
rabbit.src = './images/rabbitSpriteSheet.png';

document.addEventListener("keydown", (e) => {
    switch(e.key){
        case "s":
            frameY = 0;
            rabbitY +=speed;
            break;
        case "w":
            frameY = 1;
            rabbitY -= speed;
            break;
        case "a":
            frameY = 2;
            rabbitX -= speed;
            break;
        case "d":
            frameY = 3;
            rabbitX += speed;
            break;
        case "e":
            buttons = document.getElementsByTagName('button')
            buttonsArray = Array.from(buttons);
            var rect1 = canvas.getBoundingClientRect();
            buttonsArray.forEach((button)=>{
                let rect2 = button.getBoundingClientRect();
                var i = rabbitX + rect1.right;
                // Had to add to remove the images extra border
                if(rabbitY+50 <= rect2.bottom && rabbitX + 90 >= rect2.left && rabbitY + 95 >= rect2.top && rabbitX + 60 <= rect2.right){
                    console.log(button);
                }
            })
    }
})

function animate(){
    let CANVAS_WIDTH = canvas.width = window.innerWidth;
    let CANVAS_HEIGHT = canvas.height = window.innerHeight;

    // Cleares the screen
    ctx.clearRect(0,0,CANVAS_WIDTH, CANVAS_HEIGHT);

    let position = Math.floor(gameFrame/staggerFrames) % 4;
    frameX = spriteWidth * position;

    // Draws the rabbit, first four are cut out, second four are where it is placed (This will stretch the image)
    ctx.drawImage(rabbit,frameX,frameY * spriteHeight,spriteWidth,spriteHeight,rabbitX,rabbitY, spriteWidth * 3, spriteHeight * 3);

    gameFrame++;
    // Reccursive call
    requestAnimationFrame(animate);
}

animate();

I've solved the issue by getting all buttons on the screen using getElementsByTagName() and then computing based when e is pressed press. If there is overlap between current character and button I will then interact with the button.

Related