I have some spheres that I want to move straight on the x axis with only their y-axis changing based on the sine wave (you know the up and down yo-yo pattern). It is pretty simple in 2d but for some reason, in WEBGL, the angle changes in the sin function is not working for this.y
.
JavaScript
x
57
57
1
let particles = [];
2
let quantity = 20;
3
4
function setup() {
5
createCanvas(300, 300, WEBGL);
6
7
for (let i = 0; i < quantity; i++) {
8
let particle = new Particle();
9
particles.push(particle);
10
}
11
}
12
13
function draw() {
14
background(15);
15
orbitControl();
16
directionalLight([255], createVector(0, 0, -1));
17
translate(-width / 2, 0);
18
19
particles.forEach(particle => {
20
particle.update();
21
particle.edges();
22
particle.show();
23
});
24
};
25
26
27
// particle.js
28
function Particle() {
29
this.angle = 0;
30
this.r = 10;
31
this.x = random(width);
32
this.y = sin(this.angle) * 200; // I am changing this angle later but it's not working
33
this.z = random(-50, 50);
34
this.pos = createVector(this.x, 0, 0);
35
this.vel = createVector(2, this.y, 0);
36
37
this.update = function() {
38
this.pos.add(this.vel);
39
this.vel.limit(4);
40
this.angle += 3;
41
// print(this.pos);
42
}
43
44
this.edges = function() {
45
if (this.pos.x >= width) {
46
this.pos.x = 0;
47
}
48
}
49
50
this.show = function() {
51
noStroke();
52
push();
53
translate(this.pos.x, this.pos.y, 0);
54
sphere(this.r);
55
pop();
56
}
57
}
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
Advertisement
Answer
You only call sin
one time in the construtor. You probably meant to apply it to this.y
on every frame based on this.angle
, or some other incrementing value. Also, there are duplicate vectors; pick either an x
/y
pair or use a vector x
/y
, but not both.
JavaScript
1
52
52
1
let particles = [];
2
let quantity = 20;
3
4
function setup() {
5
createCanvas(300, 300, WEBGL);
6
7
for (let i = 0; i < quantity; i++) {
8
let particle = new Particle();
9
particles.push(particle);
10
}
11
}
12
13
function draw() {
14
background(15);
15
orbitControl();
16
directionalLight([255], createVector(0, 0, -1));
17
translate(-width / 2, 0);
18
19
particles.forEach(particle => {
20
particle.update();
21
particle.edges();
22
particle.show();
23
});
24
};
25
26
27
// particle.js
28
function Particle() {
29
this.angle = 0;
30
this.r = 10;
31
this.x = random(width);
32
this.y = 0;
33
34
this.update = function() {
35
this.angle += 0.05;
36
this.y = sin(this.angle) * 100;
37
}
38
39
this.edges = function() {
40
if (this.x >= width) {
41
this.x = 0;
42
}
43
}
44
45
this.show = function() {
46
noStroke();
47
push();
48
translate(this.x, this.y, 0);
49
sphere(this.r);
50
pop();
51
}
52
}
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>