2016-05-30 64 views
0

基本上,當我按某個方向的某個箭頭鍵時,我的三角形正在移動,但在放開鍵後停止。我想加速,然後放開鍵,讓三角形以相同的速度加速無限的時間。這裏是我的相關代碼:HTML5帆布:如何保持形狀以恆定速度無限移動

var x = 0; 
var y = 0; 
var rotationDegrees = 0; 

var movementRate = 5; 
var rotationRate = 5; 

function draw(){ 

    context.fillStyle = "rgb(0, 0, 0)"; 
    context.fillRect(0, 0, width, height); 

    drawTriangle(context, x, y, rectWidth, rectHeight, rotationDegrees); 


    if (rotationDegrees > 360){ 
     rotationDegrees = 0; 
    } 

    window.requestAnimationFrame(draw); 
} 
window.requestAnimationFrame(draw); 

window.addEventListener('keydown', function(event) { 
    console.log('this is where I describe the log: keydown event.which', event.which); 


    switch(event.which){ 
     case 37: 
     console.log('left'); 
     rotationDegrees = rotationDegrees - rotationRate; 
     break; 
     case 38: 
     console.log('up'); 
     x = x + movementRate * Math.cos(rotationDegrees * Math.PI/180); 
     y = y + movementRate * Math.sin(rotationDegrees * Math.PI/180); 
     break; 
     case 39: 
     console.log('right'); 
     rotationDegrees = rotationDegrees + rotationRate; 
     break; 
     case 40: 
     console.log('down'); 
     x = x - movementRate * Math.cos(rotationDegrees * Math.PI/180); 
     y = y - movementRate * Math.sin(rotationDegrees * Math.PI/180); 
     break; 
     default: 
    } 
}); 



function drawTriangle(context, x, y, rectWidth, rectHeight, rotationDegrees){ 
    context.save(); 

    var centerX = x + rectWidth/2; 
    var centerY = y + rectHeight/2; 

    context.translate(centerX, centerY); 

    var radians = rotationDegrees * (Math.PI/180); 
    context.rotate(radians); 



    context.strokeStyle = 'red'; 

    context.beginPath(); 


    var triangleOriginX = rectWidth/2; 
    var triangleOriginY = rectHeight/2; 

    context.moveTo(-triangleOriginX , -triangleOriginY); 
    context.lineTo(-triangleOriginX + rectWidth, -triangleOriginY + rectHeight/2); 
    context.lineTo(-triangleOriginX, -triangleOriginY + rectHeight); 

    context.closePath(); 

    context.stroke(); 

    context.restore(); 

回答

0

在你關鍵的事件處理程序代碼替換代碼設置xy與代碼中設置增量值。然後在你的主循環更新xy使用那些deltas。否則,只有在按下(正確)鍵時纔會更新位置。

// ... 
case 38: 
    dx = movementRate * Math.cos(rotationDegrees * Math.PI/180); 
    dy = movementRate * Math.sin(rotationDegrees * Math.PI/180); 
    // ... etc. 

然後在循環:

function draw(){ 
    x += dx; 
    y += dy; 

    // ...rest of code 

你當然會實現某種制衡這裏以及宣佈dxdy

+0

這工作完美!非常感謝! –