EzDevInfo.com

PhysicsJS

A modular, extendable, and easy-to-use physics engine for javascript PhysicsJS - A modular, extendable, and easy-to-use physics engine for javascript a modular, extendable, and easy-to-use physics engine for javascript

Physicsjs getTarget is undefined

I'm trying to make a custom behavior and I'm not very familiar with physicsjs. According to the docs in github I'm supposed to use var bodies = this.getTargets(); to iterate through the bodies , but I keep getting an undefined is not a function error. fiddle

What am I doing wrong?


Source: (StackOverflow)

making a body at fixed location in Physicsjs

    require.config({
    baseUrl: 'http://wellcaffeinated.net/PhysicsJS/assets/scripts/vendor/',
    packages: [
    {
    name: 'physicsjs',
    location: 'physicsjs-current',
    main: 'physicsjs-full.min'
    }
    ]
    });

    var colors = [
    ['0x268bd2', '0x0d394f']
    ,['0xc93b3b', '0x561414']
    ,['0xe25e36', '0x79231b']
    ,['0x6c71c4', '0x393f6a']
    ,['0x58c73c', '0x30641c']
    ,['0xcac34c', '0x736a2c']
    ];

    function initWorld(world, Physics) {

    // bounds of the window
    var viewWidth = window.innerWidth
    ,viewHeight = window.innerHeight
    ,viewportBounds = Physics.aabb(0, 0, window.innerWidth-50, window.innerHeight-50)
    ,edgeBounce
    ,renderer
    ,styles = {
    'circle': {
    fillStyle: colors[0][0],
    lineWidth: 1,
    strokeStyle: colors[0][1],
    angleIndicator: colors[0][1]
    }
    ,'rectangle': {
    fillStyle: colors[1][0],
    lineWidth: 1,
    strokeStyle: colors[1][1],
    angleIndicator: colors[1][1]
    }

    }
    ;

    // create a renderer
    renderer = Physics.renderer('pixi', { el: 'viewport', styles: styles });
    // add the renderer
    world.add(renderer);
    // render on each step
    world.on('step', function () {
    world.render();
    });

    // constrain objects to these bounds
    edgeBounce = Physics.behavior('edge-collision-detection', {
    aabb: viewportBounds
    ,restitution: 0.2
    ,cof: 0.8
    });

    // resize events
    window.addEventListener('resize', function () {

    // as of 0.7.0 the renderer will auto resize... so we just take the values from the renderer
    viewportBounds = Physics.aabb(0, 0, renderer.width, renderer.height);
    // update the boundaries
    edgeBounce.setAABB(viewportBounds);

    }, true);

    // add behaviors to the world
    world.add([
    Physics.behavior('constant-acceleration')
    ,Physics.behavior('body-impulse-response')
    ,Physics.behavior('body-collision-detection')
    ,Physics.behavior('sweep-prune')
    ,edgeBounce
    ]);  
    }

    function startWorld( world, Physics ){
    // subscribe to ticker to advance the simulation
    Physics.util.ticker.on(function( time ) {
    world.step( time );
    });
    }

    //
    // Add some interaction
    //
    function addInteraction( world, Physics ){
    // add the mouse interaction
    world.add(Physics.behavior('interactive', { el: world.renderer().container }));
    // add some fun extra interaction
    var attractor = Physics.behavior('attractor', {
    order: 0,
    strength: 0.002
    });

    world.on({
    'interact:poke': function( pos ){
    world.wakeUpAll();
    attractor.position( pos );
    world.add( attractor );
    }
    ,'interact:move': function( pos ){
    attractor.position( pos );
    }
    ,'interact:release': function(){
    world.wakeUpAll();
    world.remove( attractor );
    }
    });
    }
    // helper function (bind "this" to Physics)
    function makeBody( obj ){ 
    return this.body( obj.name, obj );
    }

    //
    // Add bodies to the world
    //
    function addBodies( world, Physics ){
    var v = Physics.geometry.regularPolygonVertices;
    var bodies = [
    { name: 'circle', x: 100, y: 100, vx: 0.1, radius: 60,mass:10 }

    ];
    var wallbody =[{
    name: 'rectangle', x: (innerWidth / 2) - 60,fixed:true, y: innerHeight - 30, vx: 0, width: 60, height: 300, mass: 1000, restitution: 0.0, cof: 1000
    }];//want this rectangle to be fixed like a wall

    world.add(bodies.map(makeBody.bind(Physics)));
    world.add(wallbody.map(makeBody.bind(Physics)));



    }

    //
    // Load the libraries with requirejs and create the simulation
    //
    require([
    'physicsjs',
    'pixi'
    ], function( Physics, PIXI ){
    window.PIXI = PIXI;

    var worldConfig = {
    // timestep
    timestep: 6,
    // maximum number of iterations per step
    maxIPF: 4,
    // default integrator
    integrator: 'verlet',
    // is sleeping disabled?
    sleepDisabled: false,
    // speed at which bodies wake up
    sleepSpeedLimit: 0.1,
    // variance in position below which bodies fall asleep
    sleepVarianceLimit: 2,
    // time (ms) before sleepy bodies fall asleep
    sleepTimeLimit: 500
    };

    Physics( worldConfig, [
    initWorld,
    addInteraction,
    addBodies,
    startWorld
    ]);

    });

I was trying to make a table tenis type game in which I want to make the rectangle in the body to be fixed at that location act as a wall , but when ever some object hits with it bounces due to the physics , so can somebody help me to make to turn off that objects(rectangles) physics so it stays fixed at that point


Source: (StackOverflow)

Advertisements

Why gravity acceleration is 0.0004 in PhysicsJS?

Or, perhaps, better, what does it mean?

What the units are supposed be?

If I'm trying to simulate friction against the "background", like this:

return this
    .velocityDirection
    .mult(mu * this.mass * g)
    .negate();

I expect to use g as 9.80665 m/s^2. It was working this way before PhysicsJS:

var
    frictionForce;
    frictionForce = vec2.create();
    vec2.scale(
        frictionForce,
        vec2.negate(
            frictionForce,
            this.velocityDirection
        ),
        mu * this.mass * g
    );
return frictionForce;

Was using glMatrix for my linear algebra.

I was considering mass in kilograms and forces in newtons (etc) but in PhysicsJS it doesn't seem to work like that. (For example: if I have a circle body with radius 1, it's 1 what? Cause it'll make difference when I have to use this value for something else, and when "converting" it to pixels on the screen)

Now that I'm using a physics library I feel like I'm missing some of the physics...

I Hope someone can point me in the right direction to understand it better. I'm going through the API Docs right now and learning a lot but not I'm finding the answers I'm wishing for.

UPDATE

I received a very straightforward answer. This is just to let anyone interested to know what I did then...

Thanks to Jasper and dandelany I came to understand how some of PhysicsJS works much much better. To achieve my "dream" of using inputs in newtons, metres per second squared (etc) in PhysicsJS (and also have configurable pixels per metre ratio) I decided to create another integrator.

It's just a slight variation of the original (and default) verlet integrator. I explain it, more or less, at this (crude) article Metres, Seconds and Newtons in PhysicsJS


Source: (StackOverflow)

PhysicsJS - Creating rope & attach something at the end of it

Question #1:
I'm new to PhysicsJS, and i tried to create a rope with idea of "Basket of verlet constraints"
something like this: JSFiddle
as you see, this rope is not acting natural! (friction, rope wight, stability time & ...) and by increasing the length of rope, it got worse!
first i think, by increasing the mass of ropes particles, it will slow down faster but ...

var basket = [];
var fpos = window.innerWidth / 2;
var epos = window.innerHeight / 2;
for ( var i = fpos; i < fpos + epos; i += 5 ){

    l = basket.push(
        Physics.body('circle', {
            x: i
            ,y: 50 - (i-fpos)
            ,radius: 1
            ,restitution: 0
            ,mass: 1000
            ,conf: 1
            ,hidden: true
        })
    );

    rigidConstraints.distanceConstraint( basket[ l - 1 ], basket[ l - 2 ], 2 );
}

Question #2:
after fixing that, how can i crate this:
(attaching a rectangular box at the end of rope)

enter image description here


Source: (StackOverflow)

How to setup interactive and non-interactive objects in PhysicsJS?

I am trying to setup a seesaw with userdragable objects. After world creation in PhysicsJS, mouse drag interaction is added by

world.add( Physics.behavior('interactive', { el: renderer.el }) );

which works fine. Subsequently, I want some added objects to be draggable (the box objects). But the lever should not be draggable, but it should interact with the boxes. So the lever should rotate according to a replaced box. The fulcurm is placed in a noninteractive way by setting its treatment property to static:

world.add( Physics.body('convex-polygon', {
        name: 'fulcrum',
        x: 250,
        y: 490,
        treatment: 'static',
        restitution: 0.0,
        vertices: [
            {x: 0, y: 0},
            {x: 30, y: -40},
            {x: 60, y: 0},
        ]
    }) );

How can objects be interacting with each other, but only some are userdragable?

A fiddle is available at: http://jsfiddle.net/YM8K8/


Source: (StackOverflow)

How to solve peerinvalid errors in npm install?

I'm trying to follow the steps to contribute to PhysicsJS (https://github.com/wellcaffeinated/PhysicsJS#contributing) and having the following error during npm install.

npm ERR! peerinvalid The package grunt-contrib-jasmine does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer grunt-template-jasmine-requirejs@0.1.10 wants grunt-contrib-jasmine@~0.5.3
npm ERR! System Linux 3.13.0-24-generic
npm ERR! command "/usr/bin/node" "/usr/bin/npm" "install"
npm ERR! cwd /home/slacktracer/Dropbox/dev/PhysicsJS
npm ERR! node -v v0.10.26
npm ERR! npm -v 1.4.3
npm ERR! code EPEERINVALID
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /home/slacktracer/Dropbox/dev/PhysicsJS/npm-debug.log
npm ERR! not ok code 0

Any suggestions on how to solve it?


Source: (StackOverflow)

Did drag setting changed in PhysicsJS?

I can see drag working in this fiddle using PhysicsJS 0.5.2: http://jsfiddle.net/slacktracer/z7DmA/ but it doesn't work using 0.6.0: http://jsfiddle.net/slacktracer/z7DmA/5/.

Both should have the same drag:

world.add(Physics.integrator('verlet', {
    drag: 0.5
}));

Did something (about drag) changed? (subscribe changed to on, I saw that)

The first fiddle is using this file: http://wellcaffeinated.net/PhysicsJS/examples/physicsjs-full.js

And the second is using this file: http://anzol.biz/physicsjs/physicsjs-full-0.6.0.js (it's just the latest dist on github)


Source: (StackOverflow)

PhysicsJS change circle radius

After collision of 2 dots i want they make 1 dot with double radius so my code

world.on("collisions:detected", function(data) {
    data.collisions[0].bodyA.mass *=2
    data.collisions[0].bodyA.radius *=2
    data.collisions[0].bodyB.mass = 0
    data.collisions[0].bodyA.recalc()
    data.collisions[0].bodyB.recalc()
})

Radius doesn't change and sometimes strange behavior that 2 dots dissapear at one moment.

Is my code correct?


Source: (StackOverflow)

Agregate Bodies in PhysicsJS

I would like to make a custom physicsjs body type called "player" which is a composition of 2 circles and one square. The figure would look like a square with a circle attached to the left and right sides of the square. I was thinking of just making a custom polygon into this shape, however the circles will not be true circles, but instead look more like a hexagon. Any ideas how to make physicsjs draw a curved line between verticies instead of a straight line or how to combine existing bodies into one new body?

Thanks


Source: (StackOverflow)

How to rotate fixed object using PhysicsJS?

I'm learning new javascript lib PhysicsJS (link).

If anybody can help me or show me example of:

How to rotate fixed object (like propeller and balls bounce of it)?

How to set in world some object that bounce with object that not bounce?

Edge-collision-detection (AABB) , Is it possible to do a circle instead of the cube?


Source: (StackOverflow)

PhysicsJS: Add behavior to compound body's children

I am trying to add the newtonian behavior to the children of a compound body in PhysicsJS. I have several compound bodies, and I can apply the newtonian behavior to them, but their children don't receive the behavior, which perhaps makes sense.

But when I try to add a behavior to the children of each compound it doesn't seem to apply it. Is there a way to make this work?

//create compound body
//create children bodies and append to compound body children
//create behavior and add to children compound bodies. 


//create the compound body
galaxy.element = Game.Physics.body('compound', {
    x: galaxy.x,
    y: galaxy.y,
    children: [],
});

//create the children and add them to compound
var starElements = [];
for(var i =0; i<galaxy.stars.length; i++){
    var star = galaxy.stars[i];
    star.element = Game.Physics.body('circle', {
        label: 'star',
        x: star.x,
        y: star.y,
        vx: star.vx,
        mass: star.mass,
        radius: star.radius,
        styles: {
            fillStyle: star.color
        }
    });
    galaxy.element.addChild(star.element);
    starElements.push(star.element);
}

var innerPull = Game.Physics.behavior('newtonian').applyTo(starElements);
Game.world.add(innerPull);

This is the relevant part. Here is a fiddle with the full thing. http://jsfiddle.net/gisheri/2cdyr808/


Source: (StackOverflow)

physicsjs + requirejs: can't get script to actually do anything

I'm new to using requirejs. I'm trying to use it to learn a physics module. I'm following a very basic tutorial, but I'm stuck. Basically, I want to simply create a circle using a module, but nothing is happening. Dev tools in chrome isn't throwing any errors and all the dependencies are being loaded as I'd expect.

This is the html:

<!DOCTYPE html>
<html>
    <head>
        <title>Physics project</title>
        <!-- data-main attribute tells require.js to load
             scripts/main.js after require.js loads. -->
        <script data-main="main" src="lib/require.js"></script>
        <link rel="stylesheet" type="text/css" rel='nofollow' href="lib/css/style.css"
    </head>
    <body>
        <div class="content">
        <h2>Physics</h2>
        <canvas id="viewport" width="500" height="500"></canvas>
    </div>
    </body>
</html>

main.js:

require(['lib/config/require-config'], function(){
    require(['lib/modules/template']);
});

require-config:

require.config({
    paths: {
         "jquery": "http://code.jquery.com/jquery-latest.min",
         "underscore": "lib/underscore",
         "physicsjs":"lib/physicsjs-0.6.0/physicsjs-full-0.6.0.min",

    }

template.js: All the physics stuff is just pulled from an example for the creator of the module, so it seems like I'm not "calling" the physics function correctly or something.

    define(
    [
    'underscore',
    'jquery',
    'physicsjs',
        'lib/physicsjs-0.6.0/bodies/circle'

    ], 
    function(
        Physics
   ) {

        Physics(function(world){
      var viewWidth = 500;
      var viewHeight = 500;

      var renderer = Physics.renderer('canvas', {
        el: 'viewport',
        width: viewWidth,
        height: viewHeight,
    meta: false, // don't display meta data
    styles: {
        // set colors for the circle bodies
        'circle' : {
          strokeStyle: '#351024',
          lineWidth: 1,
          fillStyle: '#d33682',
          angleIndicator: '#351024'
        }
      }
    });

  // add the renderer
  world.add( renderer );
  // render on each step
  world.on('step', function(){
    world.render();
  });

  // bounds of the window
  var viewportBounds = Physics.aabb(0, 0, viewWidth, viewHeight);

  // constrain objects to these bounds
  world.add(Physics.behavior('edge-collision-detection', {
    aabb: viewportBounds,
    restitution: 0.99,
    cof: 0.99
  }));

  // add a circle
  world.add(
    Physics.body('circle', {
        x: 50, // x-coordinate
        y: 30, // y-coordinate
        vx: 0.2, // velocity in x-direction
        vy: 0.01, // velocity in y-direction
        radius: 20
      })
    );

  // ensure objects bounce when edge collision is detected
  world.add( Physics.behavior('body-impulse-response') );

  // add some gravity
  world.add( Physics.behavior('constant-acceleration') );

  // subscribe to ticker to advance the simulation
  Physics.util.ticker.on(function( time, dt ){

    world.step( time );
  });

  // start the ticker
  Physics.util.ticker.start();

  });
  });

Source: (StackOverflow)

Allowing specific bodies to collide with edges but not with other fixed bodies

I'm using the edge-collision-detection behavior to add collisions with the edge of the viewport, and the body-impulse-response behavior to respond to these collisions so the colliding bodies will bounce off the "walls".

However, I can't seem to make body-impulse-response only work for the given bodies and the edges (body-impulse-response has no applyTo method apparently?), so now bodies are colliding with other fixed bodies even though I don't want them too.

How can I fix this issue?

Thanks!


Source: (StackOverflow)

Is there an easy way to know if a random positioned object will end up on top of an other object and trigger a collision in Physicsjs?

I am building a game which has random positioned objects inside the canvas. Depending on the quantity of objects there is a reasonable chance of getting an object placed on top of an other one and having the collision detection triggered.

Is there any easy way of preventing this in physics js?


Source: (StackOverflow)

Stop Body Rotation in PhysicsJS

I'm looking for the best practice approach to stop PhysicsJS bodies from being able to rotate. I have tried cancelling the body's rotational velocity. Yet this does not seem effective on the step as the body still somehow sneaks in some rotation. Combining this with setting the body's rotation manually seems to work at first:

world.on('step', function(){
    obj.state.angular.pos = 0;
    obj.state.angular.vel = 0;
    world.render();
});

However in the past I have experienced a lot of bugs related to this method. Seemingly to do with the object being allowed to rotate just slightly before the step is called, which causes it to be "rotated" very quickly when its body.state.angular.pos is set back to zero. This results in objects suddenly finding themselves inside the subject, or the subject suddenly finding itself inside walls/other objects. Which as you can imagine is not a desirable situation.

I also feel like setting a body's rotation so forcefully must not be the best approach and yet I can't think of a better way. So I'm wondering if there's some method in PhysicsJS that I haven't discovered yet that basically just states "this object cannot rotate", yet still allows the body to be treated as dynamic in all other ways.

Alternatively what is the "safest" approach to gaining the desired effect, I would be happy even with a generic guide not tailored to physicsJS, just something to give me an idea on what is the general best practice for controlling dynamic body rotations in a simulation.

Thanks in advance for any advice!


Source: (StackOverflow)