我需要帮助查找我的JavaScript小游戏中的错误(三个我没有得到的错误)
I need help finding errors in my JavaScript mini-game (Three error that i don't get)
这是我第一次从头开始制作迷你游戏。
谷歌浏览器在运行时给了我这些错误:
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);
};
感谢您的回复!!
你的"init"函数调用"startLoop",它调用"loop",它期望"Pair1"和"Pair2"已经初始化。 但是,"init"直到调用"startLoop"后才会初始化它们。
尝试更改"init":
function init(){
Pair1 = new Pair();
Pair2 = new Pair();
startLoop();
alert('init called');
}
我认为问题是您的函数loop
需要Pair1
和Pair2
才能存在,但init
直到调用loop
之后才这样做(通过 startloop
)。
也许这个版本的init
会起作用?
//init
function init(){
Pair1 = new Pair();
Pair2 = new Pair();
startLoop();
alert('init called');
}
相关文章:
- 为什么grunt contrib connect的中间件选项的第三个参数是未定义的
- 如何使用PHP和JS级联三个下拉列表
- 灯光问题(使用三个.js)
- 在三个.js中创建球体(例如地球)的磁力线
- 什么'这是从第三个函数上的async 1st函数获得结果的更好方法
- javascript第三个XMLHttpRequest被拒绝.但前两个是允许的
- 将循环中的两个文本框相乘,并在第三个文本框上显示结果
- 根据前两个下拉ID显示第三个下拉列表
- 在数组JS中查找三个重复项
- Meteor和S3:如何通过一次上传/编辑定义三个不同的图像
- 如何替换javascript字符串中的前三个连字符
- 保存两个模型(属于第三个模型)和一个提交
- 将文本字段限制为三个数字
- 三个js键盘旋转
- 匹配三个正则表达式中的任意一个,以先到的为准(在javascript中)
- 我需要帮助查找我的JavaScript小游戏中的错误(三个我没有得到的错误)
- JavaScript:在 XMLSerializer 错误地解析实体后,用 html 160 实体替换三个空格
- showModalDialog第三个参数错误
- 高图:第三个Y轴在错误的一侧
- 添加了三个坏的MSIE错误