Executing the process of launching an entity and then promptly erasing it from the screen

I'm really stuck on my code and could use some help. I have a ship that is shooting and aliens moving towards it. I want the bullets to hit the aliens, remove them from the canvas, and keep doing so until all the aliens are gone. I've been thinking about using coordinates to make this happen. If the bullet coordinates match the alien coordinates, I want to change the color of the alien to black so it appears as though it's disappearing. Unfortunately, my attempts at this have not been successful. Any ideas or suggestions would be greatly appreciated. Thank you.

JS

    Alien.prototype.draw = function(context) {
        if(this.x == 0) {
            context.fillStyle = "red";
        } else if(this.x == 1) {
            context.fillStyle = "yellow";
        } else {
            context.fillStyle = "blue";
        }
        context.beginPath();
        context.fillRect(this.posx, this.posy, 20 , 20);
        context.fill();
    }

        var canvas = document.getElementById("screen");
        context = canvas.getContext("2d");

        if (canvas.getContext) {

            //init the aliens array
            var aliens = [];
            for(var i = 0; i < 3; i++) {
                for(var j = 0; j < 3; j++) {
                    aliens.push(new Alien(j, i));
                }
            }

HTML

<canvas id="screen" width="300" height="500"/>

Answer №1

Responding to a query that has been addressed in this (currently deleted) post:

An issue within your code is the setTimeout() function, which is preventing the shoot() method from being executed.

Avoid using parentheses when passing a function as an argument to setTimeout - it should only be a reference. By including parentheses, you inadvertently execute the shoot() method and pass its result to setTimeout().

Please attempt the following modification, which may help progress your code:

function shoot(){
    context.fillStyle = "black";
    context.fillRect(player.x, Y2--, 5,10);
    context.fillStyle = "red";
    context.fillRect(player.x, Y2, 5,10);
    if (Y2 >= 0) {
        timer = setTimeout(shoot, 1);    /// no parentheses here
    }
    else {
        context.fillstyle = "black";
        //  context.fillRect(X2, Y2, 5,10);
        Y2 = 320;
        // context.fillRect(X+23, Y2, 5,10);
    }
}

If this resolution only partially addresses your issue, kindly provide additional information and specifics regarding your intended outcome in an updated question.

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

What is the solution to the error "Maximum update depth exceeded. Calls to setState inside componentWillUpdate or componentDidUpdate" in React?

Everything was running smoothly until this unexpected issue appeared. I attempted to change the condition to componentDidMount, but unfortunately, that didn't resolve the problem. The error is occurring in this particular function. componentDidUpd ...

"Exploring ways to implement validation for multiple email addresses in a textarea using JQuery or JavaScript, while allowing the addresses to be separated by semicol

NOTE: Each email ID must be unique. An empty string value is allowed to be added. Email IDs should be separated by semicolons and commas. Basic validation of email IDs is necessary for entry. [![ $("#d-notification").focusout(function () { var ...

When making a fetch call in React, the response is the index.html file but Chrome displays an error saying Uncaught (in promise) SyntaxError: Unexpected token < in JSON

I have been encountering an issue while trying to retrieve data from my local express server and displaying it using React. The problem appears to be that instead of fetching the data, the index.html of the React app is being returned. In the network tab o ...

Having difficulty accessing the value of a table td element in HTML using a jQuery selector

When creating a table, I utilize ng-repeat to generate table rows. Whenever the dropdown changes, a function is triggered which applies certain conditions. Based on these conditions, an object is added to an array that is bound to a scope variable. Here i ...

Differentiating Between Observables and Callbacks

Although I have experience in Javascript, my knowledge of Angular 2 and Observables is limited. While researching Observables, I noticed similarities to callbacks but couldn't find any direct comparisons between the two. Google provided insights into ...

I am having difficulty retrieving the JSON object that was sent by the servlet

$(document).ready(function() { var path = null; console.log('${pageContext.request.contextPath}/loadfile'); $.ajax({ dataType: "json", url: '${pageContext.request.contextPath}/loadfile&apos ...

Adding more dynamic parameters to the external script in index.html using Vue.js

I am looking to pass username and userEmail from the getters/user method in Vuejs, which is within index.html. Here is an example of how I would like it to be passed: <script>window.appSettings={app_id:"appId", contact_name: "Alexander ...

Tips on transmitting and receiving substantial JSON information

As a newbie in the full-stack development world, I am currently on a quest to find an efficient method for transmitting and retrieving large data between my React front-end and Express back-end while keeping memory usage to a minimum. My project involves b ...

How to use jQuery to highlight the parent element when clicking on a child element?

I'm struggling with some HTML code that looks like the following: <ul> <li class="curent"><a href="home.html">Home</a></li> <li> <a href="javascript:void(0)">Products</a> <ul ...

Function executed prior to populating $scope array

I encountered an issue with AngularJS involving a function that is called before the data array is filled. When the function is invoked in ng-init, the $scope.bookings array is not yet populated, resulting in empty data. My objective is: Retrieve all book ...

Waiting for response in AngularJS Controller and setting callback

I have developed an AngularJS application with controllers.js and factories.js that I am excited about. However, I am facing a challenge when trying to manipulate the values within the controller (retrieved from the factories). The issue is that these val ...

What is the most efficient way to find the maximum, minimum, and median values in an array?

[ 0: {"carrier": "Spicejet", "value": 2596}, 1: {"carrier": "Spicejet", "value": NaN}, 2: {"carrier": "Spicejet", "value": 2864}, 3: {"carrier": "Indig ...

What is the best way to send a POST request with parameters to a PHP backend using AJAX?

This is an updated version of a previous question that was identified as a duplicate (How can I send an AJAX POST request to PHP with parameters?) I am currently sending an AJAX request to a PHP backend. Here are the JavaScript functions used to make and ...

What are the steps to creating a custom CSS rule?

While it may seem unconventional, I can't help but wonder if it's possible to create a custom CSS rule using jQuery. Imagine being able to specify something like this in a CSS stylesheet: div { color: white; background: red; /*declaring m ...

Ordering BufferGeometries in Three.js for Accurate Rendering

After consulting the discussion on the previous inquiry, I have been working on constructing models in BufferGeometry and have come to understand that the transparent flag plays a role in the rendering order: objects with transparent materials will be rend ...

Utilize jQuery.ajaxComplete to identify the location of the AJAX request

I have an event: $(document).ajaxComplete that is functioning perfectly. Yet, I am looking to determine whether ajax took place at a particular spot within the document. Is there a method to identify which ajax call was made? $(document).ajaxComplete(fu ...

Is there a way to refresh a PHP file using Ajax?

So I have this PHP file that generates a .txt file containing the names of some photos. The thing is, new photos are constantly being added to the images folder. To address this issue, I've set up a JavaScript function on my index page that calls an A ...

Adding a list without a specific order into a paragraph with the help of jQuery

Working on a client-side class, I am in the process of changing an XHR request and getElementById function to a jQuery ajax request along with jQuery document manipulation. The task at hand is to display descriptions of items available from "Rob's Roc ...

Should the Express.js router be required directly or stored in a variable before use?

I've been pondering a performance question related to express.js. In my server.js file, I have all the routes defined and the child routes are imported as follows: const ROUTE__FOO = require('./routes/foo') const ROUTE__BAR = require(' ...

Discovering how to identify words separated by spaces within a full-text search query using regex in both PHP and JavaScript

When working with text, I need to detect words that are separated by spaces. For example, if my text is: some parent +kid -control "human right" world I want to only detect some, parent, and world. This means words without any special characters like +, ...