我正在做一个非常简单的事情,事情从屏幕顶部掉下来(一旦完成)你将不得不抓住它们。我将所有掉落的物体(瓶子)存储在一个数组中。当有一个对象时,它绘制得很好并且它的 Y 位置正常增加,但是当有多个时,它们都被赋予完全相同的 X 和 Y。我不知道是什么原因造成的。
这是整个文件:
var canvas = document.getElementById("canvas");
var canvasWidth = 600;
var canvasHeight = 500;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
var ctx = canvas.getContext("2d");
var bottle = {
x: 0,
y: 0,
hasFell: false,
height: 0,
width: 0,
src1: "water1.png",
src2: "water2.png"
}
var bottles = new Array();
bottles.length = 20;
bottleImage = new Image();
bottleImage.src = bottle.src1;
fellBottleImage = new Image();
fellBottleImage.src = bottle.src2;
var makeBottle = function(){
//If math.random above 7 add new bottle
if(Math.random() > 0.7){
var madeBottle = false;
for(var i = 0; i < bottles.length; i++){
if(bottles[i] == null){
//It only goes in here once, after it has made one bottle it exits the loop
madeBottle = true;
bottles[i] = bottle;
//These are the only things that change both the X and the Y, yet these cannot be the problem.
bottles[i].x = Math.random() * 100;
bottles[i].y = Math.random() * 100;
console.log("Made bottle: " + i + " X: " + bottles[i].x + " Y: " + bottles[i].y);
break;
}
}
if(!madeBottle){
for(var i = 0; i < bottles.length; i++){
if(bottles[i].hasFell){
bottles[i] = null;
makeBottle();
}
}
}
}
}
var gameUpdate = function(){
for(var i = 0; i < bottles.length; i++){
if(bottles[i] != null){
bottles[i].y += 1;
if(bottles[i].y > canvasHeight) bottles[i] = null;
}
}
gamePaint();
}
var gamePaint = function(){
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
for(var i = 0; i < bottles.length; i++){
if(bottles[i] != null){
ctx.drawImage(bottleImage, bottles[i].x, bottles[i].y);
}
}
}
var gameInterval = setInterval(gameUpdate, 10);
var bottleInterval = setInterval(makeBottle, 1000);