2014-09-28 104 views
-1

我正在嘗試在HTML5中放置一個簡單的「遊戲」。但是我無法獲得對角線運動的工作。 「對角線移動」僅在兩個按鈕完全同時按下時才起作用。即使那樣它移動一次。下面的代碼:帆布對角線運動

// Getting canvas, and canvas context 
    var c = document.getElementById("canvas"); 
    var ctx = c.getContext("2d"); 
    //Keymap, later passed as method parameter 
    var map = [false,false,false,false]; 
    // Top, Right, Bottom, Left 


    // Function for resetting keymap 
    var resetMap = function() { 
     for(i=0;i<map.length;i++) { 
      map[i] = false; 
     }; 
    }; 


    //Function for clearing the screen before drawing 
    var clrScrn = function() { 
     ctx.clearRect(0,0,500,500); 
    }; 

    // The player character 
    var character = function() { 
     this.x = 50; 
     this.y = 50; 
     this.h = 50; 
     this.w = 50; 
    }; 

     // Draw method of the character class 
     character.prototype.draw = function() { 
      ctx.fillRect(this.x,this.y,this.h,this.w); 
     }; 

     // The move method of the character class 
     character.prototype.move = function(map) { 


      if(map[0] === true) { 
       if(map[1] == true) { 
        this.x+=5; 
        this.y-=5; 
        console.log("Pressed at the same time"); 
       } 
       else { 
        this.y-=5; 
       } 
      } 

      else if(map[1] === true) { 
       this.x+=5; 
      }    
      else if(map[2] === true) { 
       this.y+=5; 
      }    
      else if(map[3] === true) { 
       this.x-=5; 
      } 
     }; 


    //Making a new character 
    var player = new character(); 
     player.draw(); 


    // Drawing everything on screen 
    var render = function() { 

     clrScrn(); 
     player.move(map); 
     player.draw(); 
     resetMap(); 

     requestAnimFrame(render); 
    }; 

    //Calling the render function 
    render(); 

    //Binding event listener to window,checking key down, likely the source of the problem 
    window.addEventListener("keydown",function(e){ 


     if(e.keyCode == 38 && e.keyCode == 39) { 
      map[0] = true; 
      map[1] = true; 
     } 

     else if(e.keyCode == 38) { 
      map[0] = true; 
     } 
     if(e.keyCode == 39) { 
      map[1] = true; 
     } 
     if(e.keyCode == 40) { 
      map[2] = true; 
     } 
     if(e.keyCode == 37) { 
      map[3] = true; 
     } 

     console.log(e.keyCode); 

    },false); 


    //Binding event listener to key up 
    window.addEventListener("keyup",function(e){ 
     resetMap(); 
    },false); 

回答

0

在渲染功能:

player.move(map); // you move the player 
    player.draw(); // you draw the player 
    resetMap();  // you forget all pressed keys 

resetMap()是你需要再次按下按鍵,以移動只是一個步驟的原因。

請注意,長時間按鍵時,由於鍵盤重複,水平和垂直運動可能會意外地起作用。但是你不應該依賴於遊戲的關鍵重複。您應該檢測到按鍵並單獨爲各個按鍵進行輸入,以便確定是否按下了某個按鍵。

+0

哎呀,你說得對。多麼愚蠢的錯誤。謝謝! – user2941726 2014-09-28 14:54:01