i struggle creating a sinewave.

Hey coders,

i struggle with creating a proper sinewave in p5.js, the output of "b" is "null" anyway. Does anyone have a clue what's wrong with my code? Thanks in advance!

var a;

var b;

function draw() {

    b = sin(a) * 10;

    a = a + 0.001;

    print(b);
}

In Processing it works fine. Is this a p5.js-bug?

float b;

float a;

void draw() {

    b = sin(a) * 10;

    a = a + 0.01;

    println(b);
 }
Tagged:

Answers

  • Answer ✓

    var a is not equivalent to float a. Try print(a) to see what sin(a) is working with...

    Since JS doesn't know what type of variable you're trying to create it doesn't assign it a sensible default value; so you have to do it yourself:

    var a = 0;
    var b = 0;
    
    function draw() {
    
        b = sin(a) * 10;
        a = a + 0.001;
    
        print(b);
    }
    
  • All right! Thank you @blindfish!

  • edited April 2016 Answer ✓

    Some extra notes:

    Given that variable b is only used inside function draw() and doesn't need to recall its past value, it's more appropriate to be declared as a local variable right there:

    var a = 0
    
    function draw() {
      const b = 10 * sin(a += 1e-3)
      console.log(nf(b, 0, 2), nf(a, 0, 3))
    }
    

    All Processing variants got a system variable called frameCount, which represents the # of times draw() was called back: http://p5js.org/reference/#/p5/frameCount

    Thus you can get rid of declaring variable a as global and instead go local (or even get rid of it): ;;)

    function draw() {
      const a = frameCount * 1e-3,
            b = 10 * sin(a)
    
      console.log(nf(b, 0, 2), nf(a, 0, 3))
    }
    
Sign In or Register to comment.