What methods can I use to prevent an image from moving and trigger a specific action with the press of a key?

I'm currently teaching myself web programming and also working on improving my C++ skills. However, I am facing a challenge with Javascript.

My main question is regarding how to create an "if statement" based on the location of an image.

I am in the process of developing a simple game where a cannon moves back and forth. The goal is for the user to press a button that stops the cannon and fires another image towards a target.

So far, I have created the images as well as a gif depicting the image moving from the cannon towards the target in an arc.

If the user manages to fire at the right moment when the cannon is in position, the image will hit the target successfully.

Could anyone provide guidance on creating an if statement based on the position? Alternatively, can someone explain how to stop the cannon and display the gif once fired?

Answer №1

If you want to adjust the position of your cannon, consider looking into the onkeyup() event - it responds when a key is released and triggers an action.

Most likely, it will alter the left positioning of the cannon in some way. It's recommended to set the CSS style position:absolute on your cannon and then modify the .left property using Javascript.

Below is an example of Javascript code to kickstart your project (untested):

var cannon = document.getElementById("cannonPic");
var leftlim = 200;

document.body.onkeyup = function() {
    // Remove 'px' from the left position style
    leftPosition = cannon.style.left.substring(0, cannon.style.left - 2);

    // Halt the cannon?
    if (leftPosition >= leftLim) {
        return;
    }

    // Shift the cannon to a new position
    cannon.style.left = cannon.style.left.substr(0, cannon + 10);
}

Accompanying HTML could be:

...
<img id='cannonImg' src='cannon.jpg' />
...
<script type='text/javascript' src='cannon.js' />

To address the "appear/reappear" subsection, utilize the .display attribute through Javascript:

var cannon = document.getElementById("cannonPic");

function show() {
    cannon.style.display = '';
}

function conceal() {
    cannon.style.display = 'none';
}

Just a heads-up, calculating arcs for objects may necessitate mathematical translations into two dimensions, depending on your level of precision. A delightful challenge if you're fond of math :)

Answer №2

If you want to fetch the initial position of the first image on your webpage in terms of x and y coordinates, you can use this code snippet:

let firstImg = document.getElementsByTagName('img')[0];
let xPos = firstImg.x;
let yPos = firstImg.y;

Answer №3

Adding some context, the typical way this is accomplished:

  1. You will have a main loop that controls the game's progression.
  2. During each iteration of the loop, you update the positions of in-game elements (such as cannon, projectiles, and targets) and display the updated elements on the screen.
  3. When a "fire" keypress is detected, you stop the movement of the cannon by setting its speed to 0.

You can access the object's position using various methods, but ultimately it is your game logic that dictates and tracks the positions of all objects constantly. Your game logic decides when to "draw the projectile at position (x,y)". It's important for your game logic to know the positions of objects rather than relying on queries to determine their locations through Javascript, especially in cases of straightforward and predictable movements.

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

The functionality of jQuery touch events on iOS devices is not functioning properly

I'm encountering issues with jQuery touch events on iOS devices. Here is my current script: $(document).ready(function(){ var iX = 0,iY = 0,fX = 0,fY = 0; document.addEventListener('touchstart', function(e) { ...

Error: Unable to access _rawValidators property of null object

I'm currently facing an issue with formgroup and formcontrol in Angular. When I run ng serve, it's showing an error in the console. Does anyone have a solution for this? TypeError: Cannot read properties of null (reading '_rawValidators&a ...

Check the feature that retrieves data from a `json` file

In my util file, I have a function that imports and checks whether a given sectionUUID has a video in the JSON file. import multipleVideos from '../data/videos.json' function hasSectionMultipleVideos (sectionUUID) { return multipleVideos.vide ...

Using jQuery to select the next table cell vertically

Is there a way to utilize jQuery to access the cell (td) directly below a given cell in a traditional grid-layout HTML table (where each cell spans only one row and column)? I understand that the code below will assign nextCell to the cell immediately to ...

Troubleshooting Angular JS Module Injection Issues

Lately, I've been exploring the wonders of angular JS and it has truly impressed me. However, one concept that still eludes my full understanding is injection. Despite this, I have successfully employed this technique across numerous pages in my proje ...

Displaying text on hover and showing a text box when a link is clicked using CSS and JavaScript

Hovering over the text will display "Edit," and clicking on it will reveal a text box. This function will be used to update content using ajax. HTML: <table> <thead> <tr> <th> Name </th> <th> Age </th> ...

Vue 3 - Using Emit Functionality in a Reusable and Composable File

I'm trying to utilize the emit function in my file called useGoo.ts import Swal from "sweetalert2/dist/sweetalert2.js"; export default function useModal() { const { emit } = getCurrentInstance(); function myId() { emit('id&ap ...

Is there a way to update the Angular component tag after it has been rendered?

Imagine we have a component in Angular with the selector "grid". @Component({ selector: 'grid', template: '<div>This is a grid.</div>', styleUrls: ['./grid.component.scss'] }) Now, when we include this gri ...

Invoke function within bxslider callback

I am attempting to utilize a custom function within a bxslider callback, but unfortunately, the function is not being recognized (specifically: Uncaught Reference Error: nextSlideCustom() is not a function) The current code snippet I have is as follows: ...

How can JavaScript routes be used to apply specific code to multiple pages on a website?

Can you provide guidance on how to run the same code for multiple pages using routes? Below is an example I am currently exploring: var routeManager = { _routes: {}, // Collection of routes add: function(urls, action) { urls.forEach(fun ...

The text-center alignment in Bootstrap doesn't seem to be applying to buttons

After spending a considerable amount of time trying to center two buttons in Bootstrap, I came across the "text-center" class offered by Bootstrap. However, no matter where I include this class, it doesn't seem to have any effect on the alignment of t ...

Is it possible to incorporate Nth child into JavaScript?

Is it feasible to implement an Nth Child in the following code snippet? $(function() { var count = $(".parent a").length; $(".parent div").width(function(){ return ($(".parent").width()/count)-5; }).css("margin-right","5px"); }); ...

Transition within Vuejs moves forwards and backwards, with a unique feature that allows it to skip directly to

I am in the process of developing a slider element that consists of only 2 items. My goal is to ensure that these items smoothly slide back and forth to the left and right when I click on the back or next button. While everything functions correctly when I ...

Encountering an unanticipated DOMException after transitioning to Angular 13

My Angular project is utilizing Bootstrap 4.6.2. One of the components features a table with ngb-accordion, which was functioning properly until I upgraded the project to Angular 13. Upon accessing the page containing the accordion in Angular 13, I encount ...

The addition and deletion of classes can sometimes lead to disruptions in the DOM

I've been struggling to phrase this question for a while now. I'm working on a single-page e-commerce site that operates by modifying the HTML in divs and using CSS along with JQuery to show and hide those divs. My problem arises when, occasional ...

Utilizing HighCharts' Reflow Feature for Dynamic Chart Resizing

Our Angular application utilizes highcarts-ng for implementing HighCharts. Check out the Chart Maximize and Minimize function that is currently operational: function expandChartPanel() { vm.chartMaxed = !vm.chartMaxed; viewHeader = ScopeFactory. ...

Why are the radio buttons not aligned with the text in the center?

Currently, I am in the process of building a form that includes radio buttons. However, I've encountered an issue where the text next to the radio buttons appears on a different level than the buttons themselves. How can I go about fixing this partic ...

Capture all Fetch Api AJAX requests

Is there a way to intercept all AJAX requests using the Fetch API? In the past, we were able to do this with XMLHttpRequest by implementing code similar to the following: (function() { var origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.p ...

Using JavaScript and jQuery to calculate the time difference between two values

Here is a code snippet for calculating the difference between two numbers: function calculateDifference(num1, num2) { if (num1 > num2) { return num1 - num2; } else { return num2 - num1; } } On document.ready event: var result = calculateD ...

Avoiding memory leaks in Node.js with Express framework

Dealing with memory leaks in nodejs (express.js) has been a challenge for me. I followed various tutorials online, but unlike the examples provided, identifying the source of the leak in my code has not been straightforward. Through the use of Chrome Dev T ...