Falanpin
Falanpin

Reputation: 55

Can't animate matter.js

I was trying to copy an example on the matter.js website, and I can't manage to make it work. I tried to lay out my code the same as projects which did work but nothing …

    var Engine = Matter.Engine,
    World = Matter.World,
    Bodies = Matter.Bodies;

    var world;

    var engine;
    var particles=[];

function Particles(x,y,r){
  this.x=x;
  this.y=y;
  this.d=r*2;
  this.body=Bodies.circle(x,y,r);
  World.add(world,this.body);
  this.disp=function(){
    fill(255);
    ellipse(x,y,this.d, this.d);
  }

}



function setup() {
createCanvas(600,400);
engine = Engine.create();
world=engine.world;
Engine.run(engine);
rect1=Bodies.rectangle(width/2,height/2,10,150);
World.add(world,rect1);



}

function mousePressed(){
  particles.push(new Particles(mouseX,mouseY,5));
}

function draw() {
  background(51);

Engine.update(engine);
  push();
  rectMode(CENTER);
  rect(width/2,height/2,10,150);
  pop();

  for (var i = 0; i < particles.length; i++) {
    particles[i].disp();



}}

So basically the problem is that the particles that I can create with the mouse do not move ( aswell as the rectangle ), but they are referenced in world.bodies ( when I use the console in chrome ). I have no idea why its not working… I am using p5.js as a javascipt environment ( its kinda like Processing)

Upvotes: 1

Views: 956

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42176

Please try to correctly format your code before posting it. At least use proper indentation.

But your problem is this line:

ellipse(x,y,this.d, this.d);

Whenever you draw a particle, you're using the original x and y variables passed into the constructor. You're never changing these values, so your particles never move.

You're using a physics engine, but you're never getting the position of the particles from the physics engine. To fix your problem, you need to consult the documentation for the matter.js library.

Specifically, the body documentation contains information about the body.position field, which contains the position of the body as it's being updated by the physics engine.

ellipse(this.body.position.x, this.body.position.y, this.d, this.d);

Upvotes: 3

Related Questions