【发布时间】:2019-03-09 07:52:23
【问题描述】:
我在画布上创建了很多小点,在创建过程中,它会获取它们的 x、y 坐标和它们的半径,以便稍后用于我制作的碰撞函数。即使我摆脱了它的间隔,这也会导致页面变得无响应。我认为在无响应之前要处理的功能太长了。任何帮助将非常感激。这是与我的问题相关的代码。
var foodX=[]; // array for the x coordinate of the points
var foodY=[]; // array for the y coordinate of the points
var foodR=[]; // array for the radius of the points
var points=[]; //array to store the variable used to create the points for later deletion
function drawFood() { //draws all the points on my canvas
for (var food=0; food<10000; food++) { //creates 10000 points
var foodPosX=randInt(0,10000); //create a random x coordinate between 0 and 10000 on the canvas
var foodPosY=randInt(0,10000); //create a random y coordinate between 0 and 10000 on the canvas
var r=randInt(3,5) //create a random radius create a random radius between 3 and 5
ctx.beginPath();
var point=ctx.arc(foodPosX, foodPosY, r, 0, 2*Math.PI); //this variable draws each point onto the canvas
ctx.fillStyle= colors[randInt(0,7)]; // uses an array I have with different colors so I can draw different colored points randomly
ctx.fill();
ctx.closePath();
foodX[food]=foodPosX; //stores my x coordinate in an array for the point currently being created
foodY[food]=foodPosY; //stores my y coordinate in an array for the point currently being created
foodR[food]=r; //stores the radius of the point being created
points[food]=point; //stores the variable creating the point so it can be deleted when the players collides with it
}
}
function checkCollision() {
for (var i=foodX.length-1; i<foodX.length; i--) { //loop through the array backwards to check for collisions
var fXD=Math.abs(player.pX-foodX[i]); //calculates the distance between the players x coordinate and the points x coordinate
var fYD=Math.abs(player.pY-foodY[i]); //calculates the distance between the players y coordinate and the points y coordinate
var rSum=circR+foodR[i]; //adds the radius's together for the player's radius and the foods radius
if (fXD<=rSum && fYD<=rSum) { //checks if the player is currently touching the point being checked
foodX.splice(i,1); //deletes the points x coordinate from array
foodY.splice(i, 1); //deletes the points y coordinate from array
foodR.splice(i, 1); //deletes the points radius from array
points.splice(i, 1); //deletes the point the was just collided with
eatFood(); //function for when the player eats the point
}
}
}
function randInt(min, max) { //This function creates a random integer between the selected numbers
min=Math.ceil(min);
max=Math.floor(max);
return Math.floor(Math.random()*(max-min))+min;
}
我尽量保持简短,如果它太多或太少,我很抱歉。我正在尝试创建一个类似于 agar.io 的游戏,但它只是一个离线单人游戏版本。
【问题讨论】:
-
导致页面无响应
-
我不完全确定它是否有效。该网站是否会更好地发布此内容,以便更简化功能以使页面不会无响应
-
我一定错过了关于代码无法完全运行的部分。我删除了我的评论。
-
您是否尝试过使用较小的循环并以一定的间隔运行它以防止页面无响应?
-
我投票结束这个问题,因为它属于codereview.stackexchange.com
标签: javascript arrays canvas html5-canvas simplify