Javascript canvas producing a laser beam that serves no purpose

Greetings! I am diving into JavaScript and trying my hand at creating a game. The concept is simple - a ship shooting lasers at alien spacecrafts. However, I've encountered a problem with the destroy function that has left me scratching my head. Surprisingly, the alien ships seem to survive multiple laser hits until the final blow strikes them down. I need some guidance on how to activate the destroy function as soon as any laser touches an alien craft. Below, you'll find the relevant section of code (I believe) along with a link to the jsfiddle for reference. http://jsfiddle.net/235mX/

function drawLaser(){
laserList.forEach(function(Laser){
                Laser.y = Laser.y - 1;
                Ly = Laser.y;
                Lx = Laser.x;
                ctx.beginPath();
                ctx.fillStyle = Laser.color;
                ctx.arc(Laser.x, Laser.y, 10, 2 * Math.PI, false);
                ctx.fill();
                ctx.closePath();

                ctx.beginPath();
                ctx.fillStyle = 'white';
                ctx.arc(Laser.x, Laser.y + 10, 10, 2 * Math.PI, false);
                ctx.fill();
                ctx.closePath();
            });
        }


                                if(Lx >= Ax - 30 && Lx < Ax + 30 && Ly < Ay + 30 && Ly > Ay + 10){
                    destroyX = Lx;
                    destroyY = Ly;
                    enemy1 = 0;
                    destroy();

                }
                if(Lx >= Ax + 100 - 30 && Lx < Ax + 100 + 30 && Ly < Ay + 30 && Ly > Ay + 10){
                    destroyX = Lx;
                    destroyY = Ly;
                    enemy2 = 0;
                    destroy();

                }
                if(Lx >= Ax + 200 - 30 && Lx < Ax + 200 + 30 && Ly < Ay + 30 && Ly > Ay + 10){
                    destroyX = Lx;
                    destroyY = Ly;
                    enemy3 = 0;
                    destroy();

                }
                if(Lx >= Ax + 300 - 30 && Lx < Ax + 300 + 30 && Ly < Ay + 30 && Ly > Ay + 10){
                    destroyX = Lx;
                    destroyY = Ly;
                    enemy4 = 0;
                    destroy();
                }

Answer №1

One reason why your collision detection isn't functioning properly is because it only checks for collisions with the last laser fired, instead of every enemy against every laser. To resolve this issue, consider encapsulating your collision-detection logic within a loop that iterates through each laser in the laser list.

If you had avoided using global variables, you might have caught this mistake earlier. Remember, you can declare variables locally using the keyword var. It's also a good practice to implement strict mode to prevent implicit variable creation.

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

Unable to locate the requested document using the provided query string parameter

Searching for a specific document in my database using a query string referencing a user_id from a profile schema: ProfileSchema = Schema( user_id: type: Schema.Types.ObjectId vehicules: [VehiculeSchema] home: {type:Schema.Types.ObjectId, ref: &apos ...

Ways to display information using a show/close button in React

I am currently immersed in the learning process of React. My goal is to display information about different countries using a toggleable button. However, I have encountered some obstacles along the way. There's an input field that triggers upon enteri ...

Try block must be followed by either a catch block or a finally

Currently, I am utilizing Node, Express with EJS view engine, nano for CouchDB, and encountering a perplexing error that I couldn't find any specific information about on Node or JavaScript via Stack Overflow or Google. The troublesome section of my c ...

Having issues with the POST method in node.js and express when connecting to a MySQL database

My GET method is functioning perfectly I have a database called stage4 and I am attempting to insert values into it from a frontend page The connection is established, I'm using Postman to test it first, but it keeps returning a "404 error" which is ...

Looking to display the variable values on the page even after a refresh?

I am working with three variables. The first variable will receive the initial value, while the other two will get the second value. $ids = $_GET['abc']; $minprice = $_GET['minprice']; $maxprice = $_GET['maxprice']; ...

How can you bypass classList being `undefined` in older browsers?

On modern browsers, the following code works perfectly fine. However, on legacy browsers it throws an error. What is the best way to resolve this issue? Error: TypeError: Result of expression 'document.getElementById("profile").classList' [unde ...

Discovering the div element with a corresponding data attribute and subsequently removing a class from it

My code attempt doesn't seem to be functioning as expected: $('container').find("[data-slider='" + one + "']").removeClass('hidden'); This is the complete function enclosed within a document ready function: $("#service ...

Searching through a JSON object for nested objects within objects

Currently, I have some data structured as follows: var items = [ { "id" : 1, "title" : "this", "groups" : [ {"id" : 1, "name" : "groupA"}, {"id" : 2, "name" : "groupB"} ] }, { "id" : 2, "title" : "that", ...

Node.js and Mongoose not functioning properly in collaboration

Searching for a user based on matching first and last names. router.post('/post/user/search/tag', function (req, res) { function getRegex(_query) { return { $regex: '^' + _query + '|.*' + _query, $optio ...

Guide on iterating through multiple Objects while comparing key values with a string

My goal is to iterate through multiple objects, comparing the date_created key value of each object to a specific string. These objects are retrieved from an array that I can map over to display the results. Once I loop through each object, I want to push ...

Having trouble configuring and executing Vue.js within Laravel

I am fairly new to vue.js but I have experience with laravel. With the recent release of laravel 5.3, I decided to try running a sample application using Vue. resources/js/app.js : /** * First we will load all JavaScript dependencies for this pr ...

The hidden absolute positioned div disappears once the sticky navbar becomes fixed on the page

Whenever my navbar reaches the top of the screen, the links in the dropdown menu disappear. I followed tutorials and examples from w3schools to build my webpage. Specifically: howto: js_navbar_sticky howto: css_dropdown_navbar This code snippet exempli ...

Retrieve the selected value of a Bootstrap dropdown using an onclick event with jQuery

In my HTML file, there is a table containing a button component from Bootstrap in one of the columns. When this button is clicked, a dropdown menu with three options - 'medium', 'low', 'servicerequest' appears. My goal is to r ...

Identifying Hashtags with Javascript

I am trying to identify hashtags (#example) in a string using javascript and convert them to <a href='#/tags/example'>example</a> Currently, I have this code: var text = '#hello This is an #example of some text'; text.r ...

Substitute the colon in JavaScript prior to submitting the form

I am currently working on a text input search field where I want to automatically add an escape backslash to any colon entered by the user. Below is the code snippet I have implemented so far: <form role="form" action="..." method="get"> <div ...

Export nested objects from an AngularJS JSON array to a CSV file

When I download my data into a CSV file, the display setting is showing as "[object Object]". This is not the desired outcome. https://i.stack.imgur.com/ej2UO.png The expected display should look like this: https://i.stack.imgur.com/8JJ88.png This is p ...

Tips for positioning a sticky div underneath a stationary header

I'm currently utilizing Bootstrap 4 for my project, and I am encountering an issue with maintaining a div that has the class "sticky-top" just below a fixed navbar. Despite attempting to use JavaScript to replace the CSS while scrolling, it hasn' ...

Having issues with React Nivo tooltip functionality not functioning properly on specific graphs

While using Nivo ResponsivePie to visualize some data, everything is functioning properly except for the tooltip. For some reason, the tooltip isn't appearing as it should. Interestingly, I have a heatmap and a bar graph with tooltips that are working ...

There seems to be a problem with completing the Axios post request in the Javascript Front

My front-end, built with React, is having trouble retrieving data from a third-party API through my Node.js backend. Despite using axios.post request, the response remains undefined and I'm stuck at handling the asynchronous request. It appears that t ...

Browsing through extensive data collection

Is there a quick way in Python to search through a list containing approximately 5 million strings of either 128-bit or 256-bit length and identify any duplicates? I am able to convert the strings into numbers, but I'm not sure if that will significan ...