javascript - Variables being changed for no reason -
i making simple thing things fall top of screen , (once finished) have grab them. store objects falling (bottles) inside array. when there 1 object, draws fine , it's y position increases normally, yet when there more 1 given same x , y. have no idea causing this.
this whole file:
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 = 0; < bottles.length; i++){ if(bottles[i] == null){ //it goes in here once, after has made 1 bottle exits loop madebottle = true; bottles[i] = bottle; //these things change both x , y, yet these cannot problem. bottles[i].x = math.random() * 100; bottles[i].y = math.random() * 100; console.log("made bottle: " + + " x: " + bottles[i].x + " y: " + bottles[i].y); break; } } if(!madebottle){ for(var = 0; < bottles.length; i++){ if(bottles[i].hasfell){ bottles[i] = null; makebottle(); } } } } } var gameupdate = function(){ for(var = 0; < 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 = 0; < 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);
bottles[i] = bottle;
that makes bottles[i]
, bottle
point same object. @ end of loop, still have single bottle lot of different names.
if want make bottles[i]
copy of bottle
, have copying yourself. here's 1 way:
bottles[i] = {} (var key in bottle) { bottles[i][key] = bottle[key]; }
alternatively, if bottles going start out same values, make bottle
constructor function:
function bottle() { this.x = 0; this.y = 0; this.hasfell = false; this.height = 0; this.width = 0; this.src1 = "water1.png"; this.src2 = "water2.png"; } bottle = new bottle();
...
bottle[i] = new bottle();
Comments
Post a Comment