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

Converting Strings into Variable Names in Vue.js: A Step-by-Step Guide

Hi everyone, I was wondering if there's a way to convert a string into a variable name. For example, I want to convert "minXLabel" to minXLabel so that I can use it within span tags like this: <span>{{minXLabel}</span>. I current ...

Ways to convert a JavaScript object's properties into JSON format

I am currently manually going through the properties of my javascript class to create JSON, as shown below. It feels cumbersome and I am looking to automate this process so that I don't have to make changes to the 'toJson' function every tim ...

Restarting the timer in JavaScript

How can I reset the countdown timer every time a user types into an input field? I tried using clearTimeout but it doesn't seem to work. Can anyone help me with my existing code instead of providing new code? DEMO: http://jsfiddle.net/qySNq/ Html: ...

Angular findIndex troubleshooting: solutions and tips

INFORMATION = { code: 'no1', name: 'Room 1', room: { id: 'num1', class: 'school 1' } }; DATABASE = [{ code: 'no1', name: 'Room 1', room: { id: 'num1', ...

Switch up the side navigation panel display

Hello, I am a newcomer to bootstrap and I have successfully implemented a collapsing navbar. However, I am looking for a way to make the navbar slide out from the right side when clicked on in mobile view. Can someone provide me with some JavaScript or j ...

Update the contents of TubeBufferGeometry with a new TubeBufferGeometry directly, avoiding unnecessary memory allocation

I am working with a mesh that is based on a TubeBufferGeometry. In each animation cycle, the path of the TubeBufferGeometry needs to change based on values provided at runtime. To achieve this, I want to update the geometry with a new TubeBufferGeometry ev ...

Encountering issues when attempting to establish the initial date of a react DatePicker based on the user's timezone

I am currently working on a React project and facing an issue with setting the default date of a DatePicker component to the user's timezone received from an API. Despite several attempts, I keep encountering an error whenever I try to inject the date ...

Troubleshooting a dysfunctional Vue.js component

I am currently facing a challenge in getting components to function properly. Interestingly, without the component, everything seems to be working fine (as per the commented code). Here is my HTML snippet: <strong>Total Price:</strong> <sp ...

Issue encountered when using exports in a React project - Uncaught ReferenceError: exports is not recognized

Recently, as I began my journey with React.js, I encountered a perplexing error. Within my project, there is a file that exports a function in the following format: exports.building = { //... //Something goes here... }; To import this function, I uti ...

Enhancing Security: Implementing Node.js API Authentication

Looking for guidance on setting up multiple authentications with different roles in Next.js development. Can anyone help me navigate this aspect of website building? Using Next.js for the frontend Utilizing Node.js and JWT (JSON web token) for the backend ...

Implementing location functionality in Nextjs 13+ for both server-side rendering and client-side components

I need help displaying an active link in the header navigation. Previously, I used useRoute() for versions under 13, but it stopped working in version 13 and above. Additionally, useRoute is not mounted when using SSR. To work around this issue, I ensured ...

What is the best way to avoid adding duplicate HTML content to Bootstrap modal divs using jQuery?

In my project, I wanted to create a functionality where clicking on an image would trigger a modal box to pop up with additional content added once. However, I encountered two issues that I'm currently facing. Firstly, the header text that I intended ...

Utilizing Vue Composables: Effectively Implementing Multiple Instances without State Sharing

In my VueJS application, I have a composable file that fetches information from an API and displays it in a table within two components simultaneously: // Here is a basic example of the composable implementation: export function useDatatable () { const t ...

What is the most efficient way to implement OR conditions in JavaScript for shorter code

Hello there! I have a question about optimizing conditions in code. Is there a more elegant way to write the following conditions? state === 'su' || state === 'ja' || state === 'fa' I was thinking if it could be simplified ...

I am running into a problem trying to configure the "timezone" setting for MySQL within Sequelize and Node.js

Currently, I am utilizing node and sequelize to develop a web API. So far, everything is functioning correctly. However, when attempting to update the user table with the following code: var localDate=getDateTime(); console.log(localDate) //output: 2021/06 ...

Can I transfer a variable from JavaScript to Python in a seamless way?

Here's a straightforward query: Is it possible to include a JavaScript variable (varExample) in the data.py line while preserving the functionality of the JSONP Python callback code (?callback=? part)? The objective is to seamlessly integrate varExamp ...

Tips for generating an input element using JavaScript without the need for it to have the ":valid" attribute for styling with CSS

My simple input in HTML/CSS works perfectly, but when I tried to automate the process by writing a JavaScript function to create multiple inputs, I encountered an issue. The input created with JavaScript is already considered valid (from a CSS ":valid" sta ...

The location layer on my Google Maps is not appearing

For a school project, I am working on developing a mobile-first website prototype that includes Google Maps integration. I have successfully added a ground overlay using this image, but I am facing issues with enabling the "my location layer". When I tried ...

Fetch operates based on the specified categoryId

Hey there, I'm currently in the process of learning JS and trying to fetch data from an API. I've successfully fetched all the work from api/works and displayed them in a div. Now, I'm looking to create 3 buttons that represent 3 categories ...

Struggling to establish object notation through parent-child relationships in Angular 2

Hi there, I am new to Angular and JavaScript. Currently, I am working on achieving a specific goal with some data. data = ['middlename.firstname.lastname','firstname.lastname']; During the process, I am looping through the .html usin ...