Как обнаружить объект холста, выходящий из холста? - PullRequest
0 голосов
/ 09 ноября 2019

Я пытаюсь удалить объект (ы) из массива, когда этот объект удаляется с холста. Я видел, как этот код работает для другой игры, но он не будет работать для моей. Вместо этого он удаляет объекты слишком рано из массива и не удаляет их в нужное время. Кроме того, холст является полноразмерным размером экрана пользователя. Спасибо.

Код, который я пробовал:

while (bubbleDataIndex.val < bubbleData.length) {
        if (bubbleData[bubbleDataIndex.val].x > canvasWidth) {
            bubbleData.splice(bubbleDataIndex.val, 1);
        } 
        else {
            bubbleDataIndex.val += 1;
            console.log(bubbleDataIndex.val);
        }
    }

Полный код:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var canvasWidth = canvas.width;
var canvasHeight = canvas.height;

var canvasLeft = (canvasWidth - canvasWidth);

var bubbleData = generateBubbles();
var bubbleDataIndex = {
  val: 0
};
var possibleBubbleIndex = {
  x: 0,
  y: 0
};

var currentX;
var currentY;

function generateBubbles() {
  var generatedBubbleData = []; //Array that bubbleData gets it's values from

  var bubbleCount = 0;

  var bubbleX = 0;
  var bubbleY = 0;

  function yCalc() { //Generates each circles "y" value
    var currentY;
    var mathRandom = Math.floor(Math.random() * 101);
    if (mathRandom < 21) {
      bubbleY = 600;
    }

    if (mathRandom < 41 && mathRandom > 20) {
      bubbleY = 500;
    }

    if (mathRandom < 61 && mathRandom > 40) {
      bubbleY = 400;
    }

    if (mathRandom < 81 && mathRandom > 60) {
      bubbleY = 300;
    }

    if (mathRandom < 101 && mathRandom > 80) {
      bubbleY = 200;
    }

    return currentY;
  }

  var mathRandom = Math.floor(Math.random() * 101);

  function xCalc() { //Generates each circles "x" value
    var currentX;
    if (mathRandom < 26) {
      bubbleX = Math.random() * 250;
    }

    if (mathRandom < 51 && mathRandom > 25) {
      bubbleX = Math.random() * 350;
    }

    if (mathRandom < 76 && mathRandom > 50) {
      bubbleX = Math.random() * 400;
    }

    if (mathRandom > 75) {
      bubbleX = Math.random() * 450;
    }
    return currentX;
  }

  while (bubbleCount < 25) { //Stops generating "x" and "y" values if there are 25 circles
    currentX = xCalc();
    currentY = yCalc();


    generatedBubbleData.push({ //Adding "x" and "y" values to the generatedBubbleData array
      x: bubbleX,
      y: bubbleY
    });

    if (bubbleCount <= 25) {
      bubbleCount++;
      mathRandom = Math.floor(Math.random() * 101);
      xCalc();
      yCalc();
    }
  }
  return generatedBubbleData;
}

generateBubbles();

function draw() {
  canvas.width = window.innerWidth; // Sets canvas width
  canvas.height = window.innerHeight; // +mheight, with keeping good drawing quality
  ctx.fillStyle = "red";
  ctx.beginPath();
  bubbleData.forEach(function(bubbleDataItem) { //Draws each circle
    ctx.beginPath();
    ctx.arc(bubbleDataItem.x, bubbleDataItem.y, 20, 0, 2 * Math.PI);
    ctx.closePath();
    ctx.fill();
  })
}

draw();

function update(deltaTime) {
  if (!deltaTime) return;


  bubbleData.forEach(function(b) {

  });
}

/*while(bubbleDataIndex < bubbleData.length){

    if(bubbleData[bubbleDataIndex].x > canvasWidth + 20) {
        console.log("removed");
    }

    else {
        bubbleDataIndex++;
    }

    if(bubbleData.length < 25) {

    }
}*/
//ctx.imageSmoothingEnabled = false; //Makes images clear


function gameLoop(timestamp) { //Always updates position of circles, etc.
  let lastTime = 0;
  let deltaTime = timestamp - lastTime;
  lastTime = timestamp;
  ctx.clearRect(0, 0, 800, 600);

  bubbleData.forEach(function(bblData) {
    bblData.x += 10;
    bblData.y -= 1;
  })

  while (bubbleDataIndex.val < bubbleData.length) {
    if (bubbleData[bubbleDataIndex.val].x > canvasWidth) {
      bubbleData.splice(bubbleDataIndex.val, 1);
    } else {
      bubbleDataIndex.val += 1;
      console.log(bubbleDataIndex.val);
    }
  }
  
  update(deltaTime);
  draw();

  requestAnimationFrame(gameLoop);
}

gameLoop();
<canvas id="canvas"></canvas>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...