Creating vectors as global variables

When I use createVector() to assign a vector object to a global variable I get an object error. I've been working around the issue by creating a custom object that contains the vector objects I need and assigning the custom object to a global variable. I'm curious why it isn't possible to assign vector objects to global variables, any ideas?

Answers

  • PVector p1 = new PVector (23,232);
    
  • You might look at this discussion

  • edited November 2014 Answer ✓

    At the P5.JS' "Necklace" sketch, "global" variable vel is assigned a p5.Vector from createVector():

    const vel=Object.seal(createVector());

    http://forum.processing.org/two/discussion/7294/why-doesnt-my-sketch-run-in-javascript-mode

    So I don't get why you couldn't do the same! @-)

  • Thanks GoToLoop! Didn't think to seal the vector object, that works!

  • edited November 2014 Answer ✓

    Oh, Object.seal() or Object.freeze() got nothing to do w/ it! :(|)
    Those were my attempt experiments at making objects "immutable" in JS.
    They can be removed w/o any side effects at all! :-j

    const vel = createVector();

  • I guess I should have included some code, the issue I was having was that

    function() setup{
            pos = createVector(0,0);
            vel = createVector(0,0);
    }
    
    function() draw{
            pos.add(vel);
    }
    

    was throwing me an object error. Actually now that I check, that isn't happening anymore today...

  • edited November 2014
    • It's true that pos & vel are being created as global variables inside your setup().
    • However, it's frowned upon doing so via that fashion in JS.
    • Variables should be created w/ var, const, or let keywords!

    Either declare them at the top and then initialize them within setup():

    var pos, vel;
    
    function setup() {
      pos = createVector(), vel = createVector();
    }
    
    function draw() {
      pos.add(vel);
    }
    

    Or declare & initialize them at the top:

    const pos = createVector(), vel = createVector();
    
    function draw() {
      pos.add(vel);
    }
    
Sign In or Register to comment.