2016-10-27 27 views
-1

如何更改彈跳球的大小以使其每5次變小反彈,然後每5次反彈就恢復到正常尺寸。就我自己的項目而言,我剛開始學習關於HTML5的知識。如何更改彈跳球的大小,使其每5次反彈變小一次,然後每5次彈跳就恢復到正常大小

ball.x += xunits; 
    ball.y += yunits; 
    context.fillStyle = color; 
    context.beginPath(); 
    context.arc(ball.x,ball.y,15,0,Math.PI*2,true); 
    context.closePath(); 
    context.fill(); 


    if (ball.x > theCanvas.width || ball.x < 0) { 
     angle = 180 - angle; 
     color = "red"; 
     updateBall(); 
    } else if (ball.y > theCanvas.height || ball.y < 0) { 
     angle = 360 - angle; 
     color = "blue"; 
     updateBall(); 
    } 

} 

function updateBall() { 
    radians = angle * Math.PI/ 180; 
    xunits = Math.cos(radians) * speed; 
    yunits = Math.sin(radians) * speed; 
} 

var speed = 5; 
var p1 = {x:250,y:0}; 
var angle = 45; 
var radians =0; 
var xunits = 0; 
var yunits = 0; 
var color = "blue"; 
var ball = {x:p1.x, y:p1.y}; 
updateBall(); 

theCanvas = document.getElementById('canvasOne'); 
context = theCanvas.getContext('2d'); 

function gameLoop() { 
     window.setTimeout(gameLoop, 20); 
     drawScreen()  
    } 

gameLoop(); 

回答

0

你可以使用一個計數器

var counter = 0; 

雖然反彈,增加櫃檯和adust大小

counter++; 
size -= value; 

併爲您5在那裏你可以重置計數器和大小

if (counter === 5) { 
    counter = 0; 
    // size = ... reset 
} 
0

喲,我是這可能會有太多的錯誤來幫助你排序。您在聲明之前使用變量和函數。 drawScreen未在您發佈的代碼段中聲明,並且是此處的關鍵功能。

我已經把它清理了一下,我相信它正在做你想要什麼。有些事情我更加風格化,但是我上面提到的聲明順序是而不是文體,並且是必要的。

(function(window, document){ 
var ball = {x:250, y:30}, 
    color = "blue", 
    speed = 20, 
    angle = 45, 
    radians, 
    xunits, 
    yunits, 

    theCanvas = document.getElementById('canvasOne'), 
    context = theCanvas.getContext('2d'); 

function drawScreen(){ 
    context.beginPath(); 
    context.arc(ball.x,ball.y,15,20,Math.PI*2,true); 
    context.fillStyle = color; 
    context.fill(); 
    context.closePath(); 
function updateBall(){ 
    radians = angle * Math.PI/180; 
    xunits = Math.cos(radians) * speed; 
    yunits = Math.sin(radians) * speed; 
    ball.x += xunits; 
    ball.y += yunits; 

    if (ball.x > theCanvas.width - 7.5 || ball.x < 7.5) { 
     angle = 180 - angle; 
     color = "red"; 
    } 
    if(ball.y > theCanvas.height || ball.y < 0) { 
     angle = 360 - angle; 
     color = "blue"; 
    } 
} 
    updateBall(); 
    context.clear(); 
} 
function gameLoop() { 
     window.setTimeout(gameLoop, 500); 
     drawScreen(); 
    } 
gameLoop(); 
})(this, document);