2013-03-15 45 views
1

我是JS和canvas的新手,我試圖練習一下。我試圖創造一個垂直射擊遊戲,我希望敵人不僅以線性方式移動,而且上下移動(之字形)。到目前爲止,我只能編寫線性運動,但我還沒有能夠編碼擺動運動。這是我迄今編碼(檢查drawDucks功能):使用帆布圖形的Zig Zag運動

<html> 
<head> 
    <script> 
     var c = new Object(); 
     var ctx = new Object(); 
     bg = new Image(); 
     bg.src = "bg.jpg"; 
     tank = new Image(); 
     tank.src = "tank1.png"; 
     duck = new Image(); 
     duck.src = "duck_1.png"; 
     gameCanvas = 
      {  
       tankPos : 221.5, 
       duckLeft : 0, 
       duckTop : 30, 
       getCanvas : function(id) 
        { 
         c = document.getElementById('canvas1'); 
         ctx = c.getContext('2d'); 
         setInterval(gameCanvas.drawDucks,2); 
         gameCanvas.drawGame(); 
         gameCanvas.moveTank(); 
        }, 
       drawGame : function() 
        { 
         ctx.drawImage(bg,0,0); 
         ctx.drawImage(tank,gameCanvas.tankPos,400); 
         ctx.drawImage(duck,gameCanvas.duckLeft,gameCanvas.duckTop); 
        }, 
       moveTank : function() 
        { 
         document.onkeydown = function(dir) 
          { 
           switch (dir.keyCode) 
            { 
             case 39: 
              { 
               if (gameCanvas.tankPos < 440) 
                { 
                 gameCanvas.tankPos += 20; 
                 gameCanvas.drawGame(); 
                } 
               else 
                { 
                 gameCanvas.tankPos; 
                } 
               break; 
              } 
             case 37: 
              { 
               if (gameCanvas.tankPos > 10) 
                { 
                 gameCanvas.tankPos -= 20; 
                 gameCanvas.drawGame(); 
                 break; 
                } 
              } 
             case 17: 
              { 
               gameCanvas.fire(); 
              } 
            } 
          } 
        }, 
       drawDucks : function() 
        { 
         if (gameCanvas.duckLeft < 512) 
          { 
           gameCanvas.duckLeft += 1; 
          } 
         else 
          { 
           gameCanvas.duckLeft = -75 
          } 
         gameCanvas.drawGame(); 
        } 
      } 
    </script> 
</head> 

<body onload = 'gameCanvas.getCanvas()'> 
    <canvas id = 'canvas1' width='512px' height='480px'> 
    </canvas> 
</body> 
</html> 

回答

0

當然。您需要爲運動模式的最小y和最大y設置一個變量。類似這樣的:

var direction = 'down'; 
var minY = 100; 
var maxY = 200; 
var x = 400; 
var y = 150; 
var speed = 5; 

if (direction == 'down') 
{ 
    if (y <= maxY) 
    { 
     y += speed; 
    } 
    else 
    { 
     direction = 'up'; 
    } 
} 
else if (direction == 'up') 
{ 
    if (y >= minY) 
    { 
     y -= speed; 
    } 
    else 
    { 
     direction = 'down'; 
    } 
} 
x -= speed; 

當y軸朝向畫布的左邊緣移動時,會使對象呈鋸齒形。