pixelkind / p5canvas

An interactive preview for writing p5js code in Visual Studio Code
https://marketplace.visualstudio.com/items?itemName=garrit.p5canvas
Other
39 stars 4 forks source link

edge checks with canvas #71

Open Hifilo opened 1 year ago

Hifilo commented 1 year ago

Hello,

In this script I have an edge check that should make a change when it hits the edges of the canvas

    edges() {
        if (this.p.y >= height) {
            this.p.y = height;
            this.v.y *= -1;
        }
    }

however this is the result:

Code_hEOMvG95nf

is this a bug or should I be writing the code differently?

pixelkind commented 1 year ago

Hej,

Can you post the full code? It looks like a bug, but I would like to confirm it.

Thanks :)

Hifilo commented 1 year ago

So I just copied some elements of this script for the example:

https://editor.p5js.org/codingtrain/sketches/5V8nSBOS

but i didnt save it:

let moverA;
let moverB;

function setup() {
    createCanvas(400, 400);
    moverA = new Mover(100, 200, 2);
    moverB = new Mover(300, 200, 4);
}

function draw() {
    background(0);

    if (mouseIsPressed) {
        let wind = createVector(1, 0);
        moverA.applyForce(wind);
        moverB.applyForce(wind);
    }

    let gravity = createVector(0, 0.2);
    let weightA = p5.Vector.mult(gravity, moverA.mass);
    let weightB = p5.Vector.mult(gravity, moverB.mass);
    moverA.applyForce(weightA);
    moverB.applyForce(weightB);

    moverA.update();
    moverA.edges();
    moverA.show();

    moverB.update();
    moverB.edges();
    moverB.show();
}

class Mover {
    constructor(x, y, m) {
        this.pos = createVector(x, y);
        this.vel = createVector(0, 0);
        this.acc = createVector(0, 0);
        this.mass = m;
        this.r = sqrt(this.mass) * 10;
    }

    applyForce(force) {
        let f = p5.Vector.div(force, this.mass);
        this.acc.add(f);
    }

    edges() {
        if (this.pos.y >= height - this.r) {
            this.pos.y = height - this.r;
            this.vel.y *= -1;
        }

        if (this.pos.x >= width - this.r) {
            this.pos.x = width - this.r;
            this.vel.x *= -1;
        } else if (this.pos.x <= this.r) {
            this.pos.x = this.r;
            this.vel.x *= -1;
        }
    }

    update() {

        this.vel.add(this.acc);
        this.pos.add(this.vel);
        this.acc.set(0, 0);
    }

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