2014-01-06 1 views
1

나는 자바 스크립트와 프로그래밍에 익숙하지 않으므로 많이 알고 있다고 생각하지 마십시오.자바 단순한 끝없는 게임, setTimeout 문제

저는 고속도로의 차량이 캔버스 직사각형으로 표시되는 간단한 html5 자바 스크립트 게임을 만들고 있습니다. 나는 지금 순간에 차량 산란과 움직임을 만들고있다. 내 목표는 차량이 어떤 속도로 가고 있는지에 상관없이 그들 사이에 일정한 공간이 생기도록 내버려 두는 것입니다.

어떤 지연이 발생하고 속도 변수가 4 이하의 숫자로 설정된 경우를 제외하고는 무엇이 효과가 있습니까? 나는 약간의 연구를했고, 이것이 setTimeout이 지연을 고려하지 않았기 때문에 이것이라고 생각한다. 새로운 기능이기 때문에 많은 기능을 모릅니다. 문제를 해결하는 방법에 대한 단서가 없으며 온라인에서 해결책을 찾을 수 없습니다.

내 코드 here의 작동 데모를 볼 수 있습니다 - 여는 탭과 다른 지연 현상을 일으키는 프로세스가 있으며 속도 변수를 5 이하의 숫자로 설정하면 내가 어디에서 왔는지 알 수 있습니다. 어떤 도움을 주셔서 감사합니다.

<!DOCTYPE html> 
<html> 
<body> 
<canvas id="ctx" width="480" height="320" style="border:1px solid #000000;"></canvas> 
<script> 
     var ctx = document.getElementById("ctx").getContext("2d"); 

      function setIntervalX(callback, delay, repetitions) { 
       var x = 0; 
       var intervalID = window.setInterval(function() { 
        callback(); 
        if (++x === repetitions) { 
         window.clearInterval(intervalID); 
        } 
       }, delay); 
      } 

      var speed = 50 


      function game() { 
       var yAxis 
       var selectType = Math.floor((Math.random()*6)+1) 
       switch (selectType){ 
        case 1: //semi 
        case 2: 
         yAxis = -80 
         var lane = Math.floor((Math.random()*3)+1) 
          switch (lane) 
           { 
            case 1: //left lane 
             setIntervalX(function() { 
             ctx.fillStyle = "white"; 
             ctx.fillRect(200,yAxis,15,80); 
             yAxis = yAxis + 2 
             ctx.fillStyle = "black"; 
             ctx.fillRect(200,yAxis,15,80); 
             }, speed, 400); 
            break; 
            case 2: //middle lane 
             setIntervalX(function() { 
             ctx.fillStyle = "white"; 
             ctx.fillRect(230,yAxis,15,80); 
             yAxis = yAxis + 2 
             ctx.fillStyle = "black"; 
             ctx.fillRect(230,yAxis,15,80); 
             }, speed, 400); 
            break; 
            case 3: //right lane 
             setIntervalX(function() { 
             ctx.fillStyle = "white"; 
             ctx.fillRect(260,yAxis,15,80); 
             yAxis = yAxis + 2 
             ctx.fillStyle = "black"; 
             ctx.fillRect(260,yAxis,15,80); 
             }, speed, 400); 
            break; 
           } 
         setTimeout(function() {game()}, speed * 80) 
        break;  
        case 3: //bike 
         yAxis = -10 
         var lane = Math.floor((Math.random()*3)+1) 
          switch (lane) 
           { 
            case 1: //left lane 
             setIntervalX(function() { 
             ctx.fillStyle = "white"; 
             ctx.fillRect(200,yAxis,10,10); 
             yAxis = yAxis + 2 
             ctx.fillStyle = "black"; 
             ctx.fillRect(200,yAxis,10,10); 
             }, speed, 400); 
            break; 
            case 2: //middle lane 
             setIntervalX(function() { 
             ctx.fillStyle = "white"; 
             ctx.fillRect(230,yAxis,10,10); 
             yAxis = yAxis + 2 
             ctx.fillStyle = "black"; 
             ctx.fillRect(230,yAxis,10,10); 
             }, speed, 400); 
            break; 
            case 3: //right lane 
             setIntervalX(function() { 
             ctx.fillStyle = "white"; 
             ctx.fillRect(260,yAxis,10,10); 
             yAxis = yAxis + 2 
             ctx.fillStyle = "black"; 
             ctx.fillRect(260,yAxis,10,10); 
             }, speed, 400); 
            break; 
           } 
         setTimeout(function() {game()}, speed * 45)  
        break; 
        case 4: //car 
        case 5: 
        case 6: 
         yAxis = -20 
         var lane = Math.floor((Math.random()*3)+1) 
         switch (lane) 
           { 
            case 1: //left lane 
             setIntervalX(function() { 
             ctx.fillStyle = "white"; 
             ctx.fillRect(200,yAxis,10,20); 
             yAxis = yAxis + 2 
             ctx.fillStyle = "black"; 
             ctx.fillRect(200,yAxis,10,20); 
             }, speed, 400); 
            break; 
            case 2: //middle lane 
             setIntervalX(function() { 
             ctx.fillStyle = "white"; 
             ctx.fillRect(230,yAxis,10,20); 
             yAxis = yAxis + 2 
             ctx.fillStyle = "black"; 
             ctx.fillRect(230,yAxis,10,20); 
             }, speed, 400); 
            break; 
            case 3: //right lane 
             setIntervalX(function() { 
             ctx.fillStyle = "white"; 
             ctx.fillRect(260,yAxis,10,20); 
             yAxis = yAxis + 2 
             ctx.fillStyle = "black"; 
             ctx.fillRect(260,yAxis,10,20); 
             }, speed, 400); 
            break; 
           } 
         setTimeout(function() {game()}, speed * 50)   
        break;} 
       }   
      game() 

    </script> 

    </body> 
    </html> 
+0

setInterval은 최소 실행 ** 시간 **을 보장합니다. 다른 코드가 차단되면 간격이 길어질 수 있습니다. 대신, 간격이 시작될 때마다 시간을 확인하고 마지막 반복 이후 경과 한 시간을 기반으로 수행해야 할 작업을 수행하십시오. –

+0

_ "속도 변수를 5 이하의 숫자로 설정하십시오."_ - 게임 애니메이션의 경우 작은 근처의 시간 제한/간격을 사용할 필요가 없습니다. 5ms 지연은 200 프레임/초와 같지만 20ms 간격 (50 프레임/초)은 충분히 빠릅니다. 감지 된 프레임 속도에 관계없이 간격을 너무 작게 설정하면 각 간격 사이에 필요한 모든 처리를 수행 할 수 없으므로 코드가 자체 지연을 일으킬 수 있습니다. – nnnnnn

+0

필요한 속도를 얻을 수 있도록 차량이 매번 2 픽셀 이상 움직여야합니까? – tysonsmiths

답변

1

모든 것을 업데이트하는 기본 setInterval 만 있어야합니다.
지연은 특히이 크기의 프로젝트에서 문제가되어서는 안됩니다.

+0

만약 내 이해를 위해 작동하지 않을 전체 함수에 대해 setInterval을 사용한다는 의미라면. 각 차량은 길이가 다르므로 각 차량 사이에 동일한 양의 공간이 있으므로 자체 타이머가 필요합니다. 그것의 지체가 문제를 일으키는 지 확실하지 않은 Im 그러나 속도가 그 더 낮은 수에 도착할 때 게임은 그것과 가정했던 것을하지 않는다. 그리고 내가 기울이는 can not는 그것을 고치는 것처럼 보인다. (내가 지연이라고 생각한 이유는 탭을 열어 그걸 모두 뒤죽박죽이되기 때문이다) – tysonsmiths

+0

vehicule은 길이/공간/이미지 등 다른 속성을 가진 객체 여야한다. 모두 vehicules 배열에 있어야합니다. 일반적으로 게임은 30-60 fps 사이에서 실행됩니다. 게임의 오브젝트는 모두 같은 간격으로 업데이트됩니다. 차이점은 프레임 당 얼마나 많은 픽셀이 이동하는지입니다. (예 : 0.1 픽셀) – RainingChain