Matter.js linking slider to gravity?

Hi all,

Quite a newbie here. I'm trying to make sliders for various forces to play around with in Matter.js. I'm quite confused about mapping the values, and then linking the slider to the gravity force. Here's my code so far...

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

var engine;
var world;
var boxes = [];

var ground;
var gSlider;


function setup() {
    createCanvas(400, 400);
    engine = Engine.create();
    world = engine.world;
    Engine.run(engine);

    gSlider = createSlider(0, 100, 50);
    gSlider.position(40, 365);
    gSlider.input = map(engine.world.gravity, gSlider.min, gSlider.max, 0, 1);

    var options = {
        isStatic: true
    }
    ground = Bodies.rectangle(200, height - 50, width, 10, options);
    World.add(world, ground);
}

function mousePressed() {
    if (mouseY < 350) {
        boxes.push(new Box(mouseX, mouseY, random(10, 40), random(10, 40)));
    }
}

function draw() {
    background(51);
    var fVal = gSlider.value();

    for (var i = 0; i < boxes.length; i++) {
        boxes[i].show();
    }
    noStroke();
    fill(170);
    strokeWeight(4);
    rectMode(CENTER);
    rect(ground.position.x, ground.position.y, width, 10);
    fill(255);
    textSize(15);
    text("Gravity " + fVal, 160, 381);
}

function Box(x, y, w, h, options) {
    var options = {
        friction: 0.5,
        restitution: 0.5,
    }

    this.body = Bodies.rectangle(x, y, w, h, options);
    this.w = w;
    this.h = h;
    World.add(world, this.body);

    this.show = function () {
        var pos = this.body.position;
        var angle = this.body.angle;

        push();
        translate(pos.x, pos.y);
        rotate(angle);
        rectMode(CENTER);
        strokeWeight(1);
        stroke(255);
        fill(127);
        rect(0, 0, this.w, this.h);
        pop();
    }
}

Answers

  • If you put

    gSlider.input = map(engine.world.gravity, gSlider.min, gSlider.max, 0, 1);

    in setup(), it will only run once at the beginning which means the slider input will be set to the mapped value of the gravity at the beginning only.

    If I understand correctly, maybe you're trying to do something like this in draw()?

    engine.world.gravity = map(gSlider.input, gSlider.min, gSlider.max, 0, 1);

  • Thanks for the help! I've managed to get this to work but without the mapping.

    In draw I used;

        world.gravity.y = gSlider.value() * 0.01;
    

    However it would be useful to know why the mapping doesn't work;

         gSlider.input = map(world.gravity.y, 0, 100, 0, 1);
         world.gravity.y = gSlider.value() * 0.01;
    

    This puts the gravity at 50... way too high.

Sign In or Register to comment.