javascript - 有没有办法进一步简化这些 javascript 函数?

标签 javascript arrays canvas html5-canvas simplify

我在 Canvas 上创建了很多小点,在创建过程中它获取它们的 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 的游戏,只不过它只是一个离线单人游戏版本。

最佳答案

我邀请您考虑更多地了解函数式编程范式。 几年前,我是一名游戏开发人员,我发现 FP 思维极大地清理了我的代码,并帮助我更好地概念化游戏对象。

下面是您的代码问题的部分解决方案,以 FP 风格编写;我试图表达的主要思想是

  1. 将您的 food 对象视为属性的集合,并且可以表示为单个 JS 对象。
  2. 行为(即绘制到屏幕)成为一个单独的函数,作用于单个对象
  3. 分离行为列表迭代(使用 map 功能)

代码如下:

// Assuming the ff:
// 1. an object 'ctx' exists that knows how to draw stuff
// 2. an array 'colors' exists and contains colors you have

const ctx = document.createElement('canvas').getContext('2d')

const colors = ['blue','red','yellow','black','silver','gray','navy','aqua']

// function "newRandomFood" returns a food object whose properties are randomized
function newRandomFood() {
  return {
    x: randInt(0,10000),
    y: randInt(0,10000),
    r: randInt(3,5),
    color: colors[randInt(0,7)] // uses an array I have with different colors so I can draw different colored points randomly
  }
}

// function "drawFood" draws given food object to canvas as a path
function drawFood(food) {
  ctx.beginPath();
  ctx.arc(food.x, food.y, food.r, 0, 2*Math.PI); //this variable draws each point onto the canvas. Method doesn't return anything
  ctx.fillStyle = food.color;
  ctx.fill();
  ctx.closePath();
}

// function "randInt" creates a random integer between the selected numbers
function randInt(min, max) { 
    min=Math.ceil(min);
    max=Math.floor(max);
    return Math.floor(Math.random()*(max-min))+min;
}

/* generate your foodstuffs */

const foods = Array(1000)     // create an array with 1000 elements
  .fill('')                   // fill each element with anything so iteration won't skip
  .map(_ => newRandomFood())  // fill each element with a random food item

console.log(foods)           // display all the food objects you have

foods.map(food =>             // for every food item...
     drawFood(food))          // ...draw that food

希望这有帮助。 干杯,

关于javascript - 有没有办法进一步简化这些 javascript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52637948/

相关文章:

javascript - 创建新记录后重置 Lightning-record-form

java - 将 ArrayList 转换为数组会导致崩溃

python - 将值添加到子文档中的数组(嵌套在主文档中)而不重复 - MongoDB

java - 以同样的方式对两个列表进行排序

html5 Canvas 在 IE8 中不起作用

javascript - Canvas5绘制多条线的性能问题

javascript - 如何使用 jQuery 检测任何表单输入字段的变化?

javascript - 在 Fullcalendar.js 中显示事件时出现问题

javascript - JavaScript 中的内置对象层次结构是什么样的?

javascript - 固定分辨率的大 svg 到 png