简体   繁体   中英

updating a variable jquery on event change

I am creating a interactive experience using jQuery. I am trying to make it so my character can go into multiple rooms.

$(document).keydown(function(e) {
    switch (e.which) {
        case 39:
            $("#barry").attr("src", "img/characters/BarryBallRight.png")
            $("#barry").stop().animate({
                left: 1021
            }, 1250, function() {
                position = $(this).position();
                getCurrentPos(position);
                if (barryPosX > $("#canvas").width()) {
                    if (state == 0) {
                        state = 1
                        changeBackground(state);
                        // reset barry
                        $(this).css({
                            'left': '-100px'
                        });
                        $(this).stop().animate({
                            left: '+=150px'
                        })

                    };
                    if (state == 1) {
                        state = 2;
                        changeBackground(state);
                        // reset barry
                        $(this).css({
                            'left': '-100px'
                        });
                        $(this).stop().animate({
                            left: '+=150px'
                        })
                    };
                };
            })

My problem as you can see is that the last state that runs overwrites the previous one, meaning that the changeBacktround() function will change the background of the most recent state that is set ie 2

I know there is some logic I am missing.

Note that the getCurrentPos() function just retrieves the current $("#barry") position on screen. The changeBackground() function is switch statement that takes the current state and changes the screen background accordingly.

Thanks in advance.

if (state == 0) {
   state = 1
   changeBackground(state);
   // reset barry
   $(this).css({
   'left': '-100px'
   });
  $(this).stop().animate({
  left: '+=150px'
    })

   } else if (state == 1) {
      state = 2;
      changeBackground(state);
      // reset barry
      $(this).css({
       'left': '-100px'
      });
      $(this).stop().animate({
       left: '+=150px'
        })
      };

As far as I understand you need to use else if. Right now hes always going into the 2nd condition if the state starts with 0. With else if its going either into the condition 'state == 0' or into 'state == 1' condition but not into both

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM