我正在學習這個JavaScript代碼,讓球從牆上彈開,並暫停&繼續點擊。我已經暫停了球,並希望對潛在選項提供反饋,以使用布爾值來啓用恢復。 setTimer()& stopTimer()是預定義的函數。Ball Bouncing off Walls - Pause&Resume
var ball;
var dx = 4;
var dy = 4;
var isPaused = false;
/* This program has a ball bounce around the screen. */
function start(){
ball = new Circle(20);
ball.setPosition(100, 100);
add(ball);
setTimer(draw, 20);
if(isPaused == true){
mouseClickMethod(resume);
}
}
function draw(){
checkWalls();
ball.move(dx, dy);
mouseClickMethod(pause);
}
function checkWalls(){
// Bounce off right wall
if(ball.getX() + ball.getRadius() > getWidth()){
dx = -dx;
}
// Bounce off left wall
if(ball.getX() - ball.getRadius() < 0){
dx = -dx;
}
// Bounce off bottom wall
if(ball.getY() + ball.getRadius() > getHeight()){
dy = -dy;
}
// Bounce off top wall
if(ball.getY() - ball.getRadius() < 0){
dy = -dy;
}
}
function pause(e){
var isPaused = true;
if(isPaused == true){
stopTimer(draw);
}
}
function resume(e){
var isPaused = false;
if(isPaused == false){
setTimer(draw, 20);
}
}
你需要它在純JavaScript或甚至jquery好嗎? –
那麼爲什麼你有一個函數參數暫停()和恢復()如果你不打算使用它? –
如果要執行與動畫相關的計時,可能需要查看requestAnimationFrame而不是使用setTimeout https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame – derp