2013-04-04 65 views
0

首先的工作,我做了一個動畫的Javascript畫布動畫停止與控制鍵

http://jsfiddle.net/hS2uF/

現在,我一直在努力實現這個動畫到幾個小時控制鍵,但我仍然無法找出什麼是錯:/? (它允許我控制對象雖然..)

http://jsfiddle.net/7cua6/

任何幫助將不勝感激! :)

+0

您正在調用init兩次,所以您實際上正在運行兩個立即互相覆蓋的動畫循環。 – gengkev 2013-04-04 07:56:29

+0

那麼我該如何做才能讓它工作:/? – Nucleus 2013-04-04 08:05:18

+0

任何人都可以請幫我嗎? – Nucleus 2013-04-04 08:46:10

回答

0

您需要更改以下行

imgBackground.addEventListener('load', drawBg, false); // init to drawBg 

function init(){ 
//drawBg(); remove this as you already calling on load of image 
loop(); 
document.addEventListener('keydown', checkKeyDown, false); 
document.addEventListener('keyup', checkKeyUp, false); 
} 

現在的動畫作品,但這樣你就不能正確地看到動畫您使用requestAnimationFrame其運行60fps的。所以如果你想使用requestAnimationFrame,那麼你需要有更多的精靈。

如果你不能提供更多的精靈,那麼不要使用requestAnimationFrame,而應使用setTimeout(儘管不推薦),並利用你在第一個例子中使用的10fps。

更新:

這是給你的動畫工作 Fiddle

更多更新的小提琴:

更好的FPS上移動蝌蚪改變這種

Player.prototype.checkDirection = function(){ 
if(this.isUpKey){ 
    this.drawY -= this.speed*this.width/10; // using width of the tadpole and 10fps 
} 
if(this.isRightKey){ 
    this.drawX += this.speed*this.width/10; 
} 
if(this.isDownKey){ 
    this.drawY += this.speed*this.width/10; 
} 
if(this.isLeftKey){ 
    this.drawX -= this.speed*this.width/10; 
} 
} 

Fiddle爲那

+0

謝謝,但我有幾個問題。首先該線如何影響動畫?另外,如何在不影響控制fps的情況下添加setTimeout? – Nucleus 2013-04-04 09:35:58

+0

你能告訴我哪一行嗎?對於setTimeout,你需要取出requestAnimationFrame並使用setTimeout – Sandeep 2013-04-04 09:45:00

+0

這一行:'imgBackground.addEventListener('load',drawBg,false); //初始化到drawBg '現在看起來像這樣http://jsfiddle.net/Cp9BZ/ – Nucleus 2013-04-04 09:48:27