Reputation: 601
I am Facing this Problem, my randomPoints
array element is getting replaced by push method.
Here is the output of my Console
I don't know why this is happening but if I don't use randomPoint.add
, it dosen't replaces and work fine.
randomPoint.add
retuns the same Vector object as it would return without it.
var hw
var center
var randomPoints = []
var pointWidth = 20
var points = 300
centerCircleWidth = 300;
pointsOffset = 10
function setup(){
hw = createVector(600,500)
createCanvas(hw.x,hw.y)
center = createVector(hw.x/2,hw.y/2)
var randomPoint = createVector(0,0)
randomPoints.push(randomPoint)
randomPoint = p5.Vector.fromAngle(-radians(120), random(centerCircleWidth/2-pointWidth,centerCircleWidth/2-pointsOffset))
randomPoints.push(randomPoint)
console.log(randomPoint)
randomPoint = randomPoint.add(p5.Vector.fromAngle(radians(60), random(pointsOffset,2*pointsOffset)))
// this here replaces the last element of array by itself and add another element of same type.
randomPoints.push(randomPoint)
console.log(randomPoint)
console.log(randomPoints)
}
function draw(){
translate(center.x, center.y)
background(51);
strokeWeight(0)
fill(255)
ellipse(0,0, centerCircleWidth, centerCircleWidth)
for(i=0;i<randomPoints.length;i++){
fill(10)
ellipse(randomPoints[i].x,randomPoints[i].y,pointWidth,pointWidth)
}
}
Upvotes: 1
Views: 7272
Reputation: 5688
Your problems looks to be an object reference problem. The third push
isn't replacing the previous element in the array, but you are updating the reference which the array is holding, therefore the element in the array is being updated.
If you remove the third push
, you will see that the second item in the array will still be updated.
What you need to do is either create a copy of randomPoint
and then make a change to it, or create a new variable.
Take a look at this SOF answer which should make it clearer.
Upvotes: 6