Identifying numerous array positions within a canvas

Greetings fellow developers,

Today, I have an inquiry regarding a project I am working on, akin to a Tower Defense game created using canvas. I am facing a challenge in detecting multiple circles in one coordinate. Here's an excerpt of my current dilemma:

for (var a = 0; a < buildArcherX.length; a++) {
    for (var a = 0; a < buildArcherY.length; a++) {
        if (Math.sqrt(Math.pow(buildArcherX[a] - this.x, 2) + Math.pow(buildArcherY[a] - this.y, 2)) <= arch.radius + 7) {
            this.attackedByArcher = true;
        } else {
            this.attackedByArcher = false;
        }
    }
}

In this snippet, I am utilizing arrays to store the coordinates for my "Defenses". The nested for loops iterate through all the defense coordinates in the arrays. The if statement checks if any of the defense coordinates fall within the range of "this" coordinates, returning a boolean value to indicate if any defenses are within range.

Despite reaching this point, I have encountered a roadblock: How should I handle the scenario where multiple defenses are within range? In such a case, "this" would need to sustain more damage. Therefore, I am seeking advice on whether it is feasible to display the number of defenses within range.

Appreciate your insights!

Answer №1

To keep track of how many defenses are within range, you can use an integer variable and increment it each time a defense is detected in range.

Additionally, it's important to use two separate variables when nesting loops.

this.defensesInRange = 0;
for (var a = 0; a < buildArcherX.length; a++) {
    for (var b = 0; b < buildArcherY.length; b++) {
        if (Math.sqrt(Math.pow(buildArcherX[a] - this.x, 2) + Math.pow(buildArcherY[b] - this.y, 2)) <= arch.radius + 7) {
            this.defensesInRange += 1;
        }
    }
}

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

React is up and running smoothly on my local machine, but unfortunately encountering issues on Vercel

I have encountered an issue while trying to deploy my website on Vercel. Despite the build logs showing a successful compilation, I am receiving a "failed to compile" error: [16:43:24.951] Running build in Washington, D.C., USA (East) – iad1 [16:43:25.05 ...

Using the %d method, what is the best way to incorporate an array into a text string?

Being new to Python, I've learned that when you need to insert a variable into a text string, the common format to use is "Blah blah blah %d" % some_variable This will result in "Blah blah blah some_variable" I usually manage this fine, but I se ...

Issues with expanding all nodes in the Angular Treeview function by Nick Perkins in London are causing difficulties

Currently utilizing the angular treeview project found here: https://github.com/nickperkinslondon/angular-bootstrap-nav-tree After examining the functionality, it seems that this treeview is lacking search capabilities. To address this limitation, I deci ...

Trouble updating outside controller data while using AngularJS directive inside ng-repeat loop

I am currently working with a isolate scope directive that is being used inside an ng-repeat loop. The loop iterates over an array from the controller of the template provided below: <!DOCTYPE html> <html> <head> <link rel="sty ...

Changing guid bytes into a string using JavaScript

Currently, I am receiving an arrayBuffer from a WebSocket connection and within that, I am able to obtain a range of byte arrays representing a Guid created in C#. I am wondering how I can convert these Guid bytes to a string in JavaScript? Guid: "FEF38A ...

If I remove my project but still have it saved on my GitHub, do I need to reinstall all the dependencies or can I simply run npm install again?

I have a question regarding my deleted project that is saved on GitHub. If I formatted my PC and lost the project but it's still on GitHub, do I need to reinstall all the dependencies or can I just run 'npm install'? The project has dependen ...

Prevent clicking on a specific column in a table using Jquery

Attempting to utilize Jquery for clicking on a table row in order to navigate to a new page. However, encountering an issue with the last column containing a button that redirects to a new page when clicked on the edge. Is there a way to disable the oncl ...

Guide to selecting multiple rows at once using ng-options in a list

Need assistance with an HTML list: I have a box displaying a list where users can select multiple items to save. The saving and retrieving process is functional as the selectedList stores the user's previous selections, while fullList contains all av ...

Having trouble showing an image with jQuery after it has been uploaded

Currently, I have a URL that shows an image upon loading. However, I want to provide the option for users to replace this image using a form input. My goal is to display the uploaded image as soon as it's selected so users can evaluate it. I'm a ...

React: encountering issues with accessing component props after page refresh

Whenever I try to reload the 'details' page (not the homepage) on my app, I encounter the following error: "TypeError: Cannot destructure property 'flag' of 'country' as it is undefined." It seems that the data is ...

Guidelines for transferring data when a button is held down or pressed

I am looking to continuously send values while a button is pressed. Currently, a value is only sent with each click. Below is the current code: my_custom_script.js $(document).ready(function() { $('#left').mousedown(function() { var left ...

Ways to retrieve an array saved in another JavaScript document

I am in the process of developing my own lorem ipsum application and keen on maintaining clean code by storing my word bank in separate files. How can I retrieve an array stored in a different JavaScript file? Rather than manually inputting harry = ["", "" ...

Issue with .html causing .hover to malfunction

Attempting a basic image rollover using jQuery, I've encountered an issue with the code below: HTML: <div class="secondcircle" id="circleone"> <p> <img src="/../ex/img/group1.png"> </p> </div> JS: $("# ...

Checking if a variable is true with jQuery

Check out this snippet of code: <main class="ok">My text</main> <script> $(document).ready(function() { if ( $('body').not('main.ok') ) { // or if ( Boolean ( $('main.ok') ) == false ) { ...

Saving a multi-dimensional array in a JSONArray on Android devices

I am currently working with a multidimensional array that has two columns (the number of columns is fixed but the number of rows can vary). I understand how to store a single dimensional array in a JSONArray, but I am struggling to grasp how to store a m ...

An error has occurred: sendEmail function is not defined

There seems to be a simple issue here that needs my attention before diving into PHP tasks. I plan on using PHPMailer this time around. I've been attempting to learn how to submit a form on localhost for the past week, and now I'm going to try i ...

Switch image on click (toggle between pause and play buttons)

Having some difficulty setting up a 3D audio player in A-Frame where the pause and play button images need to change depending on whether the audio is playing or not. Interested in seeing my code in action? Check it out here. ...

Exploring the hidden contents within the zip file

I have been exploring methods for reading 'zip' files. Two libraries that I have used are zip.js and JSzip. I have successfully viewed the contents of the zip file. However, here lies the challenge: My goal is to identify specific file types ...

JS animation triumphant

I have developed an app that utilizes a checkbox to control the appearance of an overlay on a screen. To ensure smooth transitions, I have incorporated animations into the process. #overlay{ position:absolute; height: 100vh; width: 100vw; ...

Error: Module 'config' not found by Jest

I have encountered an issue while using Jest to test my api calls file. When running a simple test, I received an error Cannot find module 'config' from 'api.service.js'. This error is related to the import statement at the top of my ap ...