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();
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With