简体   繁体   中英

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

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.

It appears that the console is only logging the final nested conditional else block in it's parent conditional block. In this conditional block there is no data pushed to the history property.

Only block that appears to be called in the screenshot:

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)

There is no data pushed to cycle.history in this block.

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