[英]JavaScript p5.js: ReferenceError
到目前為止,我的代碼應該能夠用蛇和食物創建一個空白畫布,每次我的蛇在食物上時,食物都應該找到一個新的位置,並且食物應該與網格上的蛇對齊。 '但現在不是。 那是我的第一個問題,在控制台中我也得到了這個錯誤:
ReferenceError: floor is not defined
請注意, floor
應該被定義p5.js 。
怎么做以及如何糾正錯誤?
這是我的代碼:
var snake;
var scl = 10;
var food;
var columns = floor(width/scl);
var rows = floor(height/scl);
function setup()
{
//Sets the Canvas
createCanvas(700, 700);
//Creates a new object using the variable snake
snake = new Snake();
food = new Food();
//Sets the frame rate
frameRate(10);
}
function draw()
{
//Sets the Background, number implies the colour
background(45);
//Adds all the values set within the function to the snake
snake.updateSnake();
snake.showSnake();
snake.keyPressed();
food.showFood();
food.updateFood();
if(snake.eatFood(food))
{
food.updateFood();
}
}
function Food()
{
this.x = random(0,700);
this.y = random(0,700);
this.updateFood = function()
{
this.pos = createVector(floor(random(columns)), floor(random(rows)));
this.pos.mult(scl);
}
this.showFood = function()
{
fill(255, 0, 10);
rect(food.x, food.y, scl, scl);
}
}
function Snake()
{
this.x = 0;
this.y = 0;
this.xspeed = 0;
this.yspeed = 0;
this.updateSnake = function()
{
this.x = this.x + this.xspeed * scl;
this.y = this.y + this.yspeed * scl;
this.x = constrain(this.x, 0, width - scl);
this.y = constrain(this.y, 0, height - scl);
}
this.showSnake = function()
{
fill(255);
rect(this.x, this.y, scl, scl);
}
this.direction = function(x, y)
{
this.xspeed = x;
this.yspeed = y;
}
this.eatFood = function(pos)
{
var distance = dist(this.x, this.y, pos.x, pos.y);
if(distance < 1)
{
return true;
console.log("WITHIN RANGE");
}else
{
return false;
console.log("OUTSIDE RANGE");
}
}
this.keyPressed = function()
{
if (keyCode === UP_ARROW)
{
snake.direction(0, -1);
} else if (keyCode === DOWN_ARROW)
{
snake.direction(0, 1);
} else if (keyCode === RIGHT_ARROW)
{
snake.direction(1, 0);
} else if (keyCode === LEFT_ARROW)
{
snake.direction(-1, 0);
}
}
}
另一個答案是使用JavaScript Math.floor()
函數。 您正在嘗試使用P5.js floor()
函數。
在調用setup()
函數之后,才能使用P5.js函數。 換句話說,您想要執行以下操作:
var columns;
var rows;
function setup()
{
//Sets the Canvas
createCanvas(700, 700);
//Creates a new object using the variable snake
snake = new Snake();
food = new Food();
//Sets the frame rate
frameRate(10);
columns = floor(width/scl);
rows = floor(height/scl);
}
在參考資料中可以找到更多信息。
(免責聲明:P5.js floor()
函數幾乎絕對是在后台使用Math.floor()
函數。但是通常,您應該盡可能使用P5.js函數。這就是它們在那里的原因。)
還要注意,出於與width
和height
變量相關的類似原因,您需要在setup()
函數中執行此操作:它們只有默認值,直到調用createCanvas()
之后。
另請參見: 為什么在setup()
之前不能使用p5函數和變量分配變量?
如果您有后續問題,請在他們自己的問題中發帖。 也請嘗試將問題縮小到MCVE,而不是發布整個草圖。 祝好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.