JavaScript movement. Changing the image by pressing the right arrow

Hi, I'm making an RPG game right now. I want to move my character with arrows. It works right now. But I want to change the image by right-clicking. Right now, when I press the right arrow with this code:

function rightArrowPressed() {
    var element = document.getElementById("image1").src = "/img/run_1.png";
    element = document.getElementById("image1");
    element.style.left = parseInt(element.style.left) + 5 + 'px';
}

Changing the image to run_1.pngant is saved. Than just the image glides in one pose. How to change the image again when I press the right arrow?

HTML

<img id="image1" src="{{Auth::user()->char_image}}" style="position:absolute;left:0; top:0;height: 45px; image-rendering: -webkit-optimize-contrast;">
+4
source share
2 answers

You can use the counter variable:

var counter = 0;
function rightArrowPressed() {
    counter = (counter === 4) ? 1 : counter+1;
    var image = "/img/run_"+counter+".png";
    var element = document.getElementById("image1");
    element.src = image;

    var left = parseInt(element.style.left)+5;
    element.style.left = left + "px";
}

And this will make it so that every time you right-click, a different image is used.

+3
source

arie imeges

function rightArrowPressed() {
    var slides=['/img/run_1.png','/img/run_2.png','/img/run_1.png'];
    slides.forEach(slide => {

         setTimeout(function(){ 
             var element = document.getElementById("image1").src = slide;
             element = document.getElementById("image1");
            element.style.left = parseInt(element.style.left) + 5 + 'px';
         }, 500);//add a time in screen
    });

}

+2

Source: https://habr.com/ru/post/1682245/


All Articles