2012-08-13 55 views
0

這是我第一次完成從零開始的迷你遊戲。我需要幫助查找我的JavaScript迷你遊戲中的錯誤(三個錯誤,我沒有得到)

谷歌瀏覽器給了我這些錯誤在運行時:

Uncaught TypeError: Cannot call method 'draw' of undefined Logic.js:28 
loop              Logic.js:28 
startLoop             Logic.js:35 
init              Logic.js:19 

這是工作正常,當我用「的setInterval」,但我想的東西,最新的。 我不認爲requestAnimationFrame與它有任何關係。

但我看不出有什麼問題!請幫忙。

// Create the canvas 
var canvas = document.getElementById("canvas"); 
var ctx = canvas.getContext("2d"); 
canvas.addEventListener('click', canvasClick, false); 

//Declarations 
var isPlaying = false; 
var animeFrame = window.requestAnimationFrame || 
       window.webkitRequestAnimationFrame || 
       window.mozRequestAnimationFrame || 
       window.msRequestAnimationFrame || 
       window.oRequestAnimationFrame; 

var Pair1; 
var Pair2; 

//init 
function init(){ 
    startLoop(); 
    Pair1 = new Pair(); 
    Pair2 = new Pair(); 
    alert('init called'); 
} 

//Draw 
function loop(){ 
    if(isPlaying){ 
     Pair1.draw(); 
     Pair2.draw(); 
     animeFrame(loop); 
    } 
} 
function startLoop(){ 
    isPlaying = true; 
    loop(); 
} 

function stopLoop(){ 
    isPlaying = false; 
} 

//Interface 
function canvasClick(){ 
    var X = event.x; 
    var Y = event.y; 

    X -= canvas.offsetLeft; 
    Y -= canvas.offsetTop; 

    if(X > Pair1.X && X < Pair1.X + 64){ 
     if(Y > Pair1.Y && Y < Pair1.Y + 96){ 
      alert('Clicked Pair1'); 
     }; 
    }; 
} 

//Create Images 
var pairImg = new Image(); 
pairImg.src = "images/Gold_Pair.png"; 
pairImg.addEventListener('load',init,false) 

//Pair 
function Pair(){ 
    var X = Math.floor(Math.random() * (canvas.width - 64)); 
    var Y = Math.floor(Math.random() * (canvas.height - 96)); 
} 

//Draw 
Pair.prototype.draw = function(){ 
    ctx.drawImage(pairImg, this.X, this.Y, 64, 96); 
}; 

感謝您的回覆!

回答

5

你的「init」函數調用「startLoop」,它調用「loop」,它預計「Pair1」和「Pair2」已經被初始化。但是,「init」不會初始化它們,直到調用「startLoop」之後的

嘗試改變「初始化」:

function init(){ 
    Pair1 = new Pair(); 
    Pair2 = new Pair(); 
    startLoop(); 
    alert('init called'); 
} 
+0

打我一秒:P – jbabey 2012-08-13 13:57:46

+0

謝謝!!!它現在不顯示錯誤...但圖像不顯示:( – Slulego 2012-08-13 14:11:12

+0

「編輯」它現在工作。我切換'var X = ....'到'this.X = ...' – Slulego 2012-08-13 14:17:38

1

我認爲問題是,你的功能loop需要Pair1Pair2存在,但init沒有做到這一點,直到後loop被稱爲(通過startloop) 。

也許這個版本的init會工作嗎?

//init 
function init(){ 
    Pair1 = new Pair(); 
    Pair2 = new Pair(); 
    startLoop(); 
    alert('init called'); 
} 
相關問題