Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138192

Why is my code is 2 ticks behind (rather than 1)?

$
0
0

Please excuse improper spacing.

Player = {
    move: function(cycle, opponent) {
      switch(cycle.current_direction) {
      case 'up':
        cycle.y -= cycle.height;
        break;
      case 'down':
        cycle.y += cycle.height;
        break;
      case 'right':
        cycle.x += cycle.width;
        break;
      case 'left':
        cycle.x -= cycle.width;
        break;
    }
    if (this.checkCollision(cycle, opponent)) {
      Game.stop(cycle);
    }
    coords = cycle.x + ',' + cycle.y;

    if(cycle.history.length > 0){
        var prev_position = cycle.history[cycle.history.length - 1]
        var pp_split = prev_position.split(',');
        var pp_x = pp_split[0]
        var pp_y = pp_split[1]

        var coords_split = coords.split(',')
        var x = coords_split[0]
        var y = coords_split[1]

        if(parseInt(x) == (parseInt(pp_x) - 4)){
            for(i=x;i>x-4;i--){
                cycle.history.push(i+','+y)
            }
        }else if (parseInt(x) == (parseInt(pp_x) + 4)){
            for(i=x;i<x+4;i++){
                cycle.history.push(i+','+y)
            }
        }else if (parseInt(y) == (parseInt(pp_y) - 4)){
            for(i=y;i>y-4;i--){
                cycle.history.push(x+','+i)
            }
        }else if (parseInt(y) == (parseInt(pp_y) + 4)){
            for(i=y;i<y+4;i++){
                cycle.history.push(x+','+i)
            }
        }else{
            console.log('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ERROR')
            console.log('cycle.history.length - 1 :' + (cycle.history.length - 1))
            console.log('x: ' + x, 'pp_x: ' + pp_x)
            console.log('y: ' + y, 'pp_y: ' + pp_y)
        }
    }else{
        cycle.history.push(coords);
    }    
},

}

My code is two ticks behind, see the console: https://imgur.com/a/rea9IIf

Desired results:

  1. (cycle.history.length-1) increases by one every loop (currently it remains 0);
  2. x is 4 -+ pp_x or y is 4 -+ pp_y, each loop

Givens:

  1. Players move 4 pixels every loop (100ms)
  2. I am calling a loop 1 tick

Any help is appreciated, thanks.


Viewing all articles
Browse latest Browse all 138192

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>