Detecting collisions on a tile map using only JavaScript

Currently, I am developing a tile-based game using a traditional method (utilizing two for loops) and struggling with writing collision detection. I want the blue square to remain on the screen and appear on top of the tiles once the start button is clicked. Amid my search for a solution, I've encountered a setback. Any assistance from the Stack Overflow community would be greatly appreciated.

Below is the code snippet:

const context = document.getElementById("canvas").getContext('2d');
const person = new rectangle(100,100,20,20,'blue');
setInterval(update_all,10);
var next_block_x = 0;
var next_block_y = 0;
var block_size = 50;
var moving = false;
const tile_map = [
    [0,0,0,0,0,0],
    [0,0,0,0,0,0],
    [1,0,0,0,0,0],
    [1,1,0,0,0,0],
    [1,1,1,0,0,0],
    [1,1,1,1,1,1]
];
function rectangle(x,y,w,h,col){
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.col = col;
    this.update = function(){
        context.fillStyle = this.col;
        context.fillRect(this.x,this.y,this.w,this.h);
        context.stroke();
    }
}
function block(x,y,col){
    this.x = x;
    this.y = y;
    this.col = col;
    context.fillStyle = this.col;
    context.fillRect(this.x,this.y,block_size,block_size);
    context.stroke();
}
function update_tile_map(){
    for(i=0;i<tile_map.length;i++){
        for(var j=0;j<tile_map[i].length;j++){
            if(tile_map[i][j] == 1){
                new block(next_block_x,next_block_y,'red');
            }
            next_block_x += block_size;
        }
        next_block_x = 0;
        next_block_y += block_size
    }
    next_block_x = 0;
    next_block_y = 0;
}
function clear(){
    context.clearRect(0,0,300,300);
}
function start(){
    moving = true;
}
function stop(){
    moving = false;
}
function update_all(){
    clear();
    update_tile_map();
    person.update();
    if(moving != false){
        person.y ++;
    }
}
#canvas{
    background-color:lightgrey;
    border: 4px solid grey;
}
<button onclick='start()'>START</button>
<button onclick='stop()'>STOP</button>
<canvas id="canvas" width='300' height='300'></canvas>

Answer №1

To ensure the block does not go beyond the wall, you can include a simple if statement:

if (person.y < 300) person.y++; else person.y = 0

const context = document.getElementById("canvas").getContext('2d');
const person = new rectangle(100,100,20,20,'blue');
setInterval(update_all,10);

var block_size = 50;
var moving = false;
const tile_map = [
    [1,1,1,1,1,1],
    [1,0,0,0,0,1],
    [1,0,0,0,0,1],
    [1,0,0,0,0,1],
    [1,0,0,0,0,1],
    [1,1,1,1,1,1]
];
function rectangle(x,y,w,h,col){
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.col = col;
    this.update = function(){
        context.fillStyle = this.col;
        context.fillRect(this.x,this.y,this.w,this.h);
        context.stroke();
    }
}


function clear(){
    context.clearRect(0,0,300,300);
}
function start(){
    moving = true;
}
function stop(){
    moving = false;
}
function update_all(){
    clear();

    person.update();
    if(moving != false){
        if (person.y < 300) person.y++; else person.y = 0
    }
}
#canvas{
    background-color:lightgrey;
    border: 4px solid grey;
}
<button onclick='start()'>START</button>
<button onclick='stop()'>STOP</button>
<canvas id="canvas" width='300' height='300'></canvas>

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

Current page with animated CSS3 menus

I found a cool menu example on this webpage: http://tympanus.net/Tutorials/CreativeCSS3AnimationMenus/index10.html. I want to modify it so that the current page's menu item has a different color from the others. For example, when I'm on the home ...

Tips for correctly deleting a duplicate ref Object ID following the removal of a Document

Coming from a background in relational databases, I'm encountering a challenge with a pattern in Mongoose. Let's say we have SchemaA and SchemaB (for example, pets and people): const Person = new Schema({ name: String, pets: [{ ref: ...

Utilizing Google Language API for bulk translation tasks

My current project involves using Google's AJAX Language API to translate each element in an array. for(var i=0; i < mytext.length; i++) { google.language.translate(mytext[i], originalLanguage, newLanguage, function(result){ if(!result.error){ ...

I am experiencing a 404 error when attempting to import a local JS file in Angular

After creating a new project with "ng new xxx", all you need to do is add one line of code in index.html: <!doctype html> <html lang="en> <head> <meta charset="utf-8> <title>Bbb</title> <base href="/&g ...

"What's the best way to update the src attribute of an iFrame when a user clicks

I'm new to coding in PHP or JavaScript, so please bear with me if my question isn't quite right. I'm looking for a way to dynamically pass and embed a URL from a link into the src attribute of an iframe. Essentially, I want users to click o ...

Vanilla JavaScript code that utilizes regex to transform JSON data into an array of blocks, while disregarding any

As I searched through various resources on converting JSON into arrays using JavaScript, none of the results matched my specific requirements (outlined below). I am in need of a RegEx that can transform JSON into an array containing all characters such as ...

Enable swipe functionality for mobile users

Looking to make the code below swipable on mobile devices. Any suggestions or resources to achieve this would be greatly appreciated! <script> var links = document.querySelectorAll(".heart"); var wrapper = document.querySelector("# ...

How can I eliminate the border appearance from a textfield fieldset component in Material-UI?

I have been struggling to remove the border using CSS code I found on Stack Overflow, but unfortunately, the issue persists. If anyone could kindly assist me in fixing this problem, I would be extremely grateful. Can someone please advise me on the specif ...

"Troubleshooting: Why is TailwindCSS not functioning correctly in my NextJS

My project utilizes a combination of NextJS, TailwindCSS, and Typescript. Strangely, everything displays correctly in the development environment, but once in production, the tailwindcss classes are not being applied. For reference, here is the link to t ...

As a newcomer to Javascript, I am currently working on developing a CRUD-based application and could use some assistance with implementing the Edit functionality

I am currently in the process of developing a Javascript CRUD application that showcases data within an HTML Table. I have successfully implemented the Create, Read, and Delete functions. However, for the Edit function, I am looking to display the data in ...

Use `$$state: {…}` within the request rather than the data

When attempting to send a request with data, I am only getting "f {$$state: {…}}" in the console. $scope.createTask = function () { var req = $http.post('api/insert', { title: $scope.newTitle, description: ...

Is there a way to send all the results of a Flask database query to a template in a way that jQuery can also access

I am currently exploring how to retrieve all data passed to a template from a jQuery function by accessing Flask's DB query. I have a database table with customer names and phone numbers, which I pass to the template using Flask's view method "db ...

Transform all the string data to integers in the JSON reply

Apologies for the basic question: This is the response I'm receiving: {id: "bitcoin", name: "Bitcoin", symbol: "BTC", rank: "1", price_usd: "15487.0"} I want to convert rank: "1", price_usd: "15487.0" to rank: 1, price_usd: 15487.0 The reason beh ...

Customize your radio buttons to display as stylish boxes with Bootstrap

Check out my Fiddle here... The radio buttons are displaying correctly in the fiddle. <div class="element-radio" title="Do you want to float the text to the left, right, or not at all?"><h4 class="title" style="font-weight: bold;">Float (left ...

Ways to adjust the text size in jqGrid?

The current theme is ui-lightness. How can I adjust the font size within the grid? Your suggestions are appreciated. Many thanks. ...

Tips for troubleshooting ImageArray loading issues in AngularJS

Having some trouble learning Angular and getting stuck with this Image array. Can someone please help me understand what's wrong with my code and how to fix it? FilterAndImages.html <!DOCTYPE html> <html ng-app="store"> <head> < ...

Preventing clicks within an iframe

Within an iframe, I have HTML content that includes hyperlinks. I need to prevent clicks on these hyperlinks. I managed to accomplish this using jQuery as shown below. However, I prefer not to use jQuery for this task. How can I achieve the same result ...

Error Uncovered: Ionic 2 Singleton Service Experiencing Issues

I have developed a User class to be used as a singleton service in multiple components. Could you please review if the Injectable() declaration is correct? import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/ht ...

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

Submit the form using the GET method and update the URL

<form method=\"GET\" action=\"http://www.$domain/search/\"> <input type=\"search\" id=\"search\" name=\"search\" value=\"terms\"> </form> This form will be directed to the follo ...