function Block(){
this.x = 100;
this.y = 100;
}
// update canvas
function UpdateCanvas(){
// check if game is still on going
if (!isStopped)
{
for(var i = segments.length - 1; i > 0 ; i--)
{
segments[i] = segments[i - 1];
}
switch(direction)
{
case "left":
segments[0].x = segments[0].x - pixelChange;
DrawCanvas();
break;
case "right":
segments[0].x = segments[0].x + pixelChange;
DrawCanvas();
break;
case "up":
segments[0].y = segments[0].y - pixelChange;
DrawCanvas();
break;
case "down":
segments[0].y = segments[0].y + pixelChange;
DrawCanvas();
break;
}
}
}
I made an array and a class called Block. Now after creating 2 objects in the array and changing blockArray[0]’s x property to a different number, blockArray[1]’s x is also changed similar to blockArray[0]’s x value instead of retaining the initial value of 100.
What was I doing wrong? and how do I change blockArray[0]’s x without affecting other objects in the array?
EDIT:
updated the code. segments is an Array with Block elements.
fixed thanks. Norguard’s and Mark Reed’s comments led me to finding the wrong part of the code (which I forgot to include on my post).
doing:
saves a reference of segments[i – 1] to segments[i] instead of a saving an object. Lesson learned for me.