Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Createvector is undefined p5js

UPDATE: Forgot to say, I'm using the p5.js editor. The rest of the sketch works, and loads the image.

When I run this code in the browser I get 'createVector is undefined'. According to the reference for p5.js I'm using the correct syntax.

Any ideas what is wrong?

var img;
var bg = 100;

var velocity = createVector(0,0);
var acceleration = createVector(0,0);

function setup() {
  createCanvas(720, 400);
  img = loadImage("assets/bb8body.png");
}

function keyPressed() {
    if (keyIsPressed === true) {
        if (key === 'd') {
            acceleration++;
            velocity.add(acceleration);

            console.log(vx);
        }
    }
}

function damping(){

}

function draw() {
    keyPressed();
    background(bg);
  image(img, velocity, 0);
  damping();
}
like image 382
chrleon Avatar asked Sep 16 '25 01:09

chrleon


1 Answers

I'm not 100% why, but createVector() works in setup() (not outside). Additionally, I've spotted two small errors:

acceleration++;

This won't work as js doesn't support overloaded operators like c++, but you can use p5.Vector's add() function. Also, the vx variable doesn't exist in the rest of your code.

Here's a modified version of your code using p5.Vector instances, but drawing a small box instead of the image, for testing purposes. You can run the demo bellow:

var img;
var bg = 100;

var velocity;// = createVector(0,0);
var acceleration;// = createVector(0,0);

function setup() {
  createCanvas(720, 400);
  velocity = createVector(0,0);
  acceleration = createVector(0,0);
  //img = loadImage("assets/bb8body.png");
}

function keyPressed() {
    if (keyIsPressed === true) {
        if (key === 'd') {
            //acceleration++;
            acceleration.add(1,1);
            velocity.add(acceleration);

            //console.log(vx);
            console.log(velocity.x);
        }
    }
}

function damping(){

}

function draw() {
    keyPressed();
    background(bg);
    rect(velocity.x,velocity.y,20,20)
  //image(img, velocity, 0);
  damping();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.22/p5.min.js"></script>
like image 148
George Profenza Avatar answered Sep 17 '25 19:09

George Profenza