Michael Moreno
Michael Moreno

Reputation: 1349

p5.js not recognizing code in other files

Working in VSCode on a p5.js project. In one file I create a blob class and give it a createVector function, then in sketch.js I create an instance of blob and call blob.createVector() in function setup(). For some reason it's completely breaking and the console logs:

Uncaught (in promise) ReferenceError: createVector is not defined
    at new Blob (blob.js:2)
    at p5.sound.min.js:2
    at Array.map 

File Structure:

|-- blob.js
|-- index.html
|-- jsconfig.json
|-- libraries
|   |-- p5.min.js
|   |-- p5.sound.min.js
|-- sketch.js
|-- style.css

sketch.js:

var blob;

function setup() {
  blob = new Blob();
  createCanvas(600, 600);
}

function draw() {
  background(0);
  blob.show();
}

blob.js:

function Blob() {
  this.pos = createVector(width/2, height/2);
  this.r = 64;

  this.show = function() {
    fill(255);
    ellipse(this.pos.x, this.pos.y, this.r*2, this.r*2);
  }
}

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Sketch</title>

    <link rel="stylesheet" type="text/css" href="style.css">

    <script src="libraries/p5.min.js"></script>
    <script src="libraries/p5.sound.min.js"></script>
  </head>

  <body>
    <script src="sketch.js"></script>
    <script src="blob.js"></script>
  </body>
</html>

Upvotes: 0

Views: 772

Answers (2)

Cimi88
Cimi88

Reputation: 11

you have to import the blob.js in the sketch.js

import './blob.js';

var blob;

function setup() {
  blob = new Blob();
  createCanvas(600, 600);
}

function draw() {
  background(0);
  blob.show();
}

Upvotes: 0

xImperiak
xImperiak

Reputation: 384

The problem is that you create the canvas after you have created the blob, and in the constructor, you are using the widht and height properties wich are inicialised when creating the canvas. That means that the only thing you have to do is to change the order as following:

var blob;

function setup() {
  createCanvas(600, 600);
  blob = new Blob();
  
}

function draw() {
  
  background(0);
  blob.show();
}
class Blob{
  
  constructor(){
    this.pos = createVector(width/2, height/2);
    this.r = 64;
  }

  show(){
    fill(255);
    ellipse(this.pos.x, this.pos.y, this.r*2, this.r*2);
  }
}

If you check this site you will see that your class constructing approach is a bit outdated. I would try to do it how it is done here.

Upvotes: 2

Related Questions