Error-free JS animation on console, but does not work

Asked

Viewed 51 times

0

Well, I am creating an animation of the Tank of the classic Metal Slug, however, when creating the function and executing it to animate the tank, nothing happens. What’s wrong, and how can I fix it?

<body>
    <div id="tank-slug">
    </div>
</body>
</html>
<style type="text/css">
    #tank-slug{
        width:196px;
        height:196px;
        margin:0 auto;
        background: url(images/Sprite-Tank-novo.png);
        background-position: 0px -10px;
        position:relative;
        overflow:hidden;
        border:2px solid #000;
    }
    #tank-slug:before{
        content:url(images/Sprite-Background.png);
        width:196px;
        height:196px;
        bottom:0;
        position:absolute;
        z-index:-1;
    }
    #tank-slug:after{
        content:url(images/Sprite-Frontground.png);
        width:196px;
        height:196px;
        bottom:0;
        position:absolute;

    }
</style>
<script type="text/javascript">
    function iniciaAnima(){
        setInterval(function(){
            var tankBack = document.getElementById("tank-slug");
            var count = 0;
            var valor = 100/55;
            var backPositionX = 0;
            tankBack.style.backgroundPosition = backPositionX + "px -10px";
            if(count < 100){ return count = count + valor }
            backPositionX = backPositionX + 190;
            console.log(tankBack.style.backgroundPosition)
            console.log(count);
        },500);
    }iniciaAnima();
</script>
  • And this var backPositionX = 0; should not be outside the setInterval?, so it’s being erased every time setInterval runs...

1 answer

2


Try it this way :

function iniciaAnima(){
    var tankBack = document.getElementById("tank-slug");
    var count = 0;
    var valor = 100/55;
    var backPositionX = 0;
    setInterval(function(){
        tankBack.style.backgroundPosition = backPositionX + "px -10px";
        if(count < 100){ return count = count + valor }
        backPositionX = backPositionX + 190;
        console.log(tankBack.style.backgroundPosition)
        console.log(count);
    },500);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.