Detecting collisions between two squares in an HTML5 canvas

class Snake {
    constructor() {
        this.x = 400;
        this.y = 400;
        this.width = 25;
        this.height = 25;
    }
    
    draw() {
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
}
let snake = new Snake();

class Food {
    constructor() {
        this.x = Math.floor(Math.random() * (canvasWidth - 0) + 0)
        this.y = Math.floor(Math.random() * (canvasHeight - 0) + 0)
        this.width = 50;
        this.height = 50;
/*         this.image = new Image()
        this.image.src = 'img/apple.png' */
    }
    update() {
    } 
    draw() {
/*         ctx.drawImage(this.image, this.x, this.y, this.width, this.height); */
ctx.fillRect(this.x, this.y, this.width, this.height);

    }
}
let food = new Food() 
function collision(){
    if(snake.x < food.x + food.width &&
        snake.x + snake.width > food.x &&
        snake.y < food.y + food.height  &&
        snake.height + snake.y > food.y){
            alert("hit")

        } 
}
collision()

I have created two classes in JavaScript, one for a snake and the other for food. I am attempting to implement a collision algorithm I found, but it doesn't seem to be working properly. Can anyone help me identify the mistake or suggest a better way to handle collisions?

Answer №1

Needed to invoke the collision function inside animate()

function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    snake.draw();
    snake.update();
    food.draw()
    collision()

    requestAnimationFrame(animate);
}
animate();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on sharing a Vue project with other devices within a network

I'm a complete beginner when it comes to vue.js. After working on a few small projects, I want to make sure I understand how to share a vue project with others at this stage. Typically, I know that running 'npm run serve' in my project dir ...

Exploring a JavaScript function that triggers another function to create a new object - Utilizing Sinon and Mocha for testing purposes

I am currently working on a nodejs application where I need to write a test for a function that invokes another function to create a new object, and then calls a method of that object. Below is the code in service.js that I am trying to test; // servic ...

Cloning a checkbox using Jquery

I am working on a search page that utilizes checkboxes to display results. After the user selects certain options and triggers a reload of the page, I want to provide an easy way for them to remove their selections by displaying them at the top of the page ...

Tips for crafting interactive Dropdown menus

Visit this link for more information Hello all, I am a beginner in HTML and Javascript and seeking guidance on how to create dynamic dropdown menus similar to the ones on the provided website. I have successfully implemented the source code, but my questi ...

What is the correct location to store the bower.json file?

I'm currently using bower 1.2.2 to handle my client-side libraries for the first time with a new node app. I'm unsure whether I should initialize bower in the main project root alongside gruntfile.js and package.json, or within the static directo ...

Connecting JavaScript and jQuery scripts

Help needed! I am a beginner in the world of jQuery and JS. Unfortunately, my JS/jQuery code is not running and I can't figure out why. Can someone please take a look at my HTML and guide me on what might be causing the issue? Do I need to add some ad ...

detect mouse click coordinates within an iframe that spans multiple domains

I am currently encountering an issue with tracking click position over a cross-domain iframe. Here is my current code: <div class="poin"> <iframe width="640" height="360" src="http://cross_domain" frameborder="0" allowfullscreen id="video">< ...

"How to retrieve the height of an element within a flexslider component

I need some assistance with using JavaScript to determine the height of an element within a flexslider. There are two challenges I am facing. When I attempt to use a regular function getHeight(){ var h = document.getElementById("id-height").style.height; ...

Converting Epoch timestamp to AM/PM format in a React render function

I am currently working on a personal project using React.js. I have successfully fetched an API, and one of the values returned is an Epoch timestamp. My goal is to display this timestamp in a human-readable format such as am/pm. The Epoch timestamp is dis ...

As the second line of Javascript code is being executed, the first line is still

I have a task where I need to execute a SQL SELECT statement and save the results. Then, those results need to be passed into a function to generate a graph using the data points provided. Refer to the code snippet below for details. var dataKWhr = getCov ...

How to add vertical bars within ng-repeat in AngularJS

I attempted to retrieve values from an array variable using ng-repeat within unordered lists. Although the values are displaying correctly and everything is functioning properly, I added vertical bars after each value to represent sub-categories on my page ...

CORS blocking Axios POST request to Heroku causing a Network Error 503

Using the MERN Stack, everything was functioning correctly until modifications were made to the UI (such as relocating code to different components and altering styles). The issue lies with a specific POST request, while other requests that utilize Axio ...

Switching from using ngRouter to ui-router is a common

After purchasing an angularjs template for my application, I noticed that ngRouter was used instead of ui-router, which I am more comfortable with. So, I decided to switch to ui-router and update all the routes. However, I encountered some extra code in my ...

Removing single quotes and replacing them with spaces when passing data from JavaScript to MySQL

I'm currently focused on JavaScript using Hapi.js in my role at the company. My main task involves retrieving data from MongoDB and transferring it to a MySQL database. The challenge arises when dealing with data that contains single quotes within th ...

What are the steps for incorporating a YouTube playlist into a website?

I'm in the process of creating a website and I'd like to incorporate a YouTube video playlist that looks similar to this example - http://www.youtube.com/user/icicibank/home. I plan to use HTML5, JavaScript, and the YouTube API. Can you provide g ...

Is there a foolproof method to authenticate form submissions using Javascript/Ajax instead of relying on PHP?

Currently, my process of handling HTML form submissions is done in PHP where I submit the form to a PHP file that: Verifies against a cookie created at page load to prevent CSRF. Includes a require_once() function for validation purposes. Executes other ...

Modifying the data attribute within the div does not result in a different image for the 360-degree spin view

My current project involves utilizing js-cloudimage-360-view.min.js to create a 360-degree view of images. I have successfully retrieved the images, but I am encountering difficulty in updating the images by clicking a button. index.html <!DOCTYPE html ...

When utilizing VueJs, it's not possible to retrieve a data property from within a function

I am encountering a challenge when trying to access the data property within the function. Despite my efforts, I seem to be missing something crucial and unable to pinpoint what it is. Here is my class: export default { name: "Contact", component ...

Is it possible to use jQuery/JS to automatically format currency input as it is typed, adding a 1000 separator and ensuring

I'm working on a text input field that needs to format the value as it is being typed, with restrictions of 2 decimal places and 1000 separators. This field should only allow for digits to be entered. Specifically, this input is meant for users to ent ...

Tips for updating a JSON object value in Node.js

Storing a JSON object in a JSON file is important for passing data during an API call. To update the object, replace "it-goes-here" with the following {} block. Newly updated data: { "parenturl":"xxx.com", "user ...