Firing a gun

As part of my journey to learn about coding in HTML/JS/CSS, I decided to create a top-down shooter game. While I've successfully implemented player movement and rotation on the canvas, I'm struggling with getting the gun mechanics to work properly.

After following tutorials and searching through StackOverflow posts, I defined a variable 'gunfire' set to 1 when the left mouse button is pressed and 0 otherwise. My aim is to draw bullets in front of the sprite when the mouse button is clicked. However, the issue I'm facing is that the bullets appear regardless of the mouse input.

If anyone can help pinpoint the error in my code, I would greatly appreciate it. Here's the snippet (the canvas is created in separate HTML/CSS files):

 // Your JavaScript code goes here

Answer №1

Firstly, Kippie points out that the issue lies in setting gunfire to 1 each time, resulting in a true statement. This must be adjusted to == or === (the latter being preferable) or eliminating the comparison altogether as any non-zero value would evaluate to true:

if (gunfire) {
   ...
}

Secondly, it's important to note that checking for mouse clicks within a key handler is not appropriate as keyCode does not pertain to mouse button clicks. In this context, keyCode of 1 has no correlation to mouse clicks.

Thirdly, there is a lack of event handlers for mouse clicks...

To address these issues (in addition to the first one), include an event handler specifically for mouse clicks:

top_canvas.addEventListener("mousedown", mouseDown, false);
window.addEventListener("mouseup",   mouseUp,   false);

Then, within the handlers (illustrated here focusing on mouse down events):

function mouseDown(e) {

    if (e.button === 0) { // verifying left mouse-button click
        gunfire = 1;
    }
}

The rationale behind using the window object for the mouse up event is to ensure that even if the mouse pointer is outside the canvas element, the release event will still register, preventing continuous firing. By utilizing the window object, you can successfully capture the up event under such circumstances.

Answer №2

if (gunfire == 1)

Instead of using the assignment operator, consider using the comparison operator. Switch to === for better practice.

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

Confirm the Text Box with JavaScript

I'm struggling with validating the textbox on my login Xhtml. Once I finally cracked the code, I encountered an issue with the 'container' class in the section. How can I properly write the code and successfully validate the textbox? <h ...

Customizing Bootstrap Vue to prevent tooltips from opening on hover

I am currently using a tooltip similar to the example shown on Toggle Tooltip: <template> <div class="text-center"> <div> <b-button id="tooltip-button-1" variant="primary">I have a tooltip</b-button> </div& ...

Passing a date string from the Controller to JavaScript using the AJAX method

Below is the controller I have written: [HttpPost] public JsonResult GetTrackList(POS_model item) { //item.item_code //item.track_type if (item.track_type != "Regular") { POS pos = new POS(); ...

What could be causing the else statement to execute in this particular node script?

Currently working on the learnyounode exercises. This function involves listing a directory and filtering files by extension. My understanding was that if an invalid directory name is provided, it would enter the if clause and exit. However, it seems to go ...

Strange Behavior of Anchor Tags

I've been struggling with my anchor tag not working properly. The desired URL is localhost/VShroff/home/about.php, but it keeps changing to localhost/about.php without redirecting. I've spent a long time trying to figure this out. Here is the HT ...

Timeout for browser response

Currently working on Perl CGI scripting within HTML, my script utilizes send expect and print statements. To prevent the browser from displaying the send expect results, I included $exp->log_user(0). When running the script in the browser, only the prin ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

Unable to change the value of selected items in checkbox event within a React context

Today marks the beginning of my journey into developing a React application. I am currently faced with the challenge of retrieving the row ID of a checked checkbox in a React table. Utilizing hooks, I have managed to transfer the states to another compone ...

Is your toggle() function failing to work on dynamically loaded ajax content?

$('.slideArrow').toggle(function (event) { //some code }, function (event) { //some code }); This code functions correctly for content loaded during the page load process. However, it fails to work for content loaded via ajax requests. The ...

Mysterious error arises in Internet Explorer versions 7 and 8: An expected colon is missing

One of our websites is encountering a puzzling JS error in Internet Explorer. The console displays the following message: ':' expected javascript:false, Line 1 Character 24 When attempting to trace the source of the error, a notification appear ...

Use Enums instead of conditions in Typescript

Consider the code snippet below, which is a function that generates a CSS class based on the value of toCheck: const computeSomething = (toCheck: string) => { return clsx('flex', { 'flex-start': toCheck === 'FIRST', ...

I encountered an issue when trying to include the dotenv file, receiving the following error message: [TypeError: Network request failed]

babel.config.js File plugins: [ ["module:react-native-dotenv", { "envName": "APP_ENV", "moduleName": "@env", "path": ".env", "blocklist": null, "allowlist": null, "blacklist": null, // DEPRECATED "whitelist": ...

Incorporating a HTML layout with a JS backdrop

I have successfully implemented a JavaScript background and now I want to apply this background across all my PHP files. The issue is that the HTML code either overlaps with the JS content or appears behind it. How can I resolve this? Below is the JS fil ...

Is it possible to comment out classes within a specified class attribute? How can this be achieved?

Is there a way to temporarily omit specific classes within HTML (<div class="" ...>)? For instance: <div data-group="group1" data-container="true" class="container-lg d-flex /* slider */ p-0"> In this s ...

Resizing webpages for mobile devices results in misaligned rows

I'm currently using Bootstrap on a website and encountering issues with the responsiveness of rows on mobile devices. The desired outcome is for rows to be divided into 4 equal sections per row on larger screens, then scale down to 2 equal sections p ...

Drag and drop functionality in Jquery using unique data-ids

I am new to using drag and drop features. Jquery : function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { var dataId = ev.target.parentNode.getAttribute('data-id'); alert("Data Id : "+dataId); var selectedTable =$ ...

Trouble injecting factory into controller using Jasmine and requireJS

I'm encountering some difficulties when trying to inject my factory into testing spec. My setup involves using requireJS to inject controllers and factories. define(['controller', 'loginFactory', 'angular', 'ang ...

Each time `fs.writeFile` is invoked, it initiates a fresh line

Every time this code is run, I want it to create a new line of data instead of overwriting the previous one. For example, if it's executed once, it would display: Checked Status: ONLINE. However, upon subsequent runs, it should add another line direc ...

Using Node.js to send a response only after every promise has been resolved

I am currently working on a NodeJS Express route where I have encountered an issue. In this route, a function is called multiple times, each returning a Promise. The values from these Promises are then added to an Array and sent back to the client using re ...

Is it possible to use a single function to both set the state and return JSX?

I'm currently grappling with creating a function that, when called, will update the state to an object {item: 'whatever the user types', list: [...list, todo]}. The challenge I'm facing is figuring out how to update the state and return ...