我是javascript的新手。我编写了以下代码:
function Vec2(x_,y_)
{
this.x = x_;
this.y = y_;
}
稍后在文件中我创建了一个这样的函数:
// Init game field array
var initGameField = function () {
var screenCenter = vec2(canvas.width / 2, canvas.height / 2);
var index = 0;
// Init gamefieldArray
for(var y = 0; y < maxVerticalBubbles; y++)
{
if(y%2)
{
for(var x = 0; x < maxHorizontalBubbles - 1; x++)
{
var initPoint = vec2(cellSize / 2 + (screenCenter.x - ((maxVerticalBubbles - 1) * cellSize / 2)) + (x * cellSize),
canvas.height / 2 + (cellSize / 2) + y * cellSize / 1.1);
gameFieldArray[index] = initPoint;
}
}
else
{
for(var x = 0; x < maxHorizontalBubbles; x++)
{
var initPoint = vec2(cellSize / 2 + (screenCenter.x - (maxVerticalBubbles * cellSize / 2)) + (x * cellSize),
canvas.height / 2 + (cellSize / 2) + y * cellSize / 1.1);
gameFieldArray[index] = initPoint;
}
}
}
}
但是当我尝试在javascript -file的末尾运行initGameField函数时,我在“initGameField”内部“vec2未定义”时出现错误......应该如何以正确的方式完成?为什么在initGameField -function之前和运行initGameField -function之前引入了vec2函数?
答案 0 :(得分:8)
Javascript区分大小写,您的函数定义为 Vec2 ,但您尝试使用 vec2
调用它还要确保使用“new”关键字创建新实例。
var initPoint = new Vec2(cellSize / 2 + (screenCenter.x - ((maxVerticalBubbles - 1) * cellSize / 2)) + (x * cellSize),
canvas.height / 2 + (cellSize / 2) + y * cellSize / 1.1);