Bob Bob - 1 month ago 6x
Javascript Question

Detecting multiple array coordinates in canvas

Hello fellow programmers,

Today I have a question that's related to one of my projects I'm making kinda like Tower Defense using canvas. However, I stuck on trying to detect multiple circles in one coordinate. Here's my example:

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;

As you can see in this example, I'm using arrays to put my coordinates in for my "Defenses". The for statements runs through all the "defense" coordinates in the arrays. The if statement in the code calculates if any of the defense coordinates are within "this" coordinates. This returns a boolean if any of the defenses are in range.

However I got to this point, and then got stuck on this problem: What happens if multiple defenses are in range? Then "this" would need to take more damage. So I'm just wondering if I can show the number of defenses in range.



You can use an integer to store the value of how many defenses are in range and increment it whenever a defense has been found in range.

Also, you must use 2 different variables when nesting loops.

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