Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop an image from moving and cause an action based on a keystroke?

Tags:

javascript

I am teaching myself web programming. I'm also working on C++. I am having a problem with Javascript.

I need to know how to create an "if statement" based on the location of an image.

I am making a simple game that has a cannon that is moving back and forth. I want the user to press a button that will cause the cannon to stop and fire launching another image toward the target.

I have already created the images and a gif of the image that will travel from the cannon in an arc toward the target.

If the user fires when the cannon is in the correct position the image will hit the target.

Can someone tell me how to create an if statement based on position? Or can someone tell me how to make the cannon stop and make the gif appear?

like image 714
user1644781 Avatar asked Dec 30 '25 06:12

user1644781


1 Answers

To move the cannon, read up on the onkeyup() event - it will wait for when a key is released, and do something.

What will it do? Probably change the left position of the cannon somehow. I'd recommend setting the CSS style position:absolute on your cannon, then changing the .left property with Javascript.

For example, here's some Javascript to get you started (untested):

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

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

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

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

And its companion HTML would look like...

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

The HTML could be styled like this:

#cannonPic {
    left:0;
    position:absolute;
}

To answer your "appear/reappear" sub-question, you can use the .display property, accessed via Javascript:

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

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

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

A small word of warning, things traveling in arcs will require some math to translate them in two dimensions, depending on how accurate you want it. A fun exercise though if you like math :)

like image 129
Ben Avatar answered Dec 31 '25 19:12

Ben