physics,famo.us , Famo.us physics engine: forces and walls not behaving as expected


Famo.us physics engine: forces and walls not behaving as expected

Question:

Tag: physics,famo.us

I am tyring to create a grid of particles, using the famous physics engine. I thought that if 25 particles were placed beteween 4 bounding walls (forming a square) and they all had an equal repulsion force to each other, they would naturally form a grid - ie. they would all be held as far away from each other as possible, given the limits of their world. I expected this to work, even if the particles were just added without an initial position. However, even if I give them an initial position, they don't hold in place unless the force is very small.

Also, I thought that if a wall had a restitution of 0, then a particle would just stop on colliding with it. When I run the code below, I can see particles bouncing off walls. The pen is at: http://codepen.io/timsig/pen/pJJrOa

What am I failing to grasp? - thanks in advance

define('main', function (require, exports, module) {
     // import dependencies
    var Engine = require('famous/core/Engine');
    var Surface = require('famous/core/Surface')
    var Modifier = require('famous/core/Modifier');
    var PhysicsEngine = require('famous/physics/PhysicsEngine');
    var Particle = require('famous/physics/bodies/Particle');
    var Drag = require('famous/physics/forces/Drag');
    var RepulsionForce = require('famous/physics/forces/Repulsion');
    var Wall            = require('famous/physics/constraints/Wall');

    var gridItems = [];

    var positionsArray = [-140,-70,0,70,140];

    var context = Engine.createContext();

    var physics = new PhysicsEngine();




    var gridR = new RepulsionForce({
        strength: 0.015
    });

    //physics.addBody(planetParticle);
  var leftWall    = new Wall({normal : [1,0,0],  distance : 140, restitution : 0});
    var rightWall   = new Wall({normal : [-1,0,0], distance : 140, restitution : 0});
    var topWall     = new Wall({normal : [0,1,0],  distance : 140, restitution : 0});
    var bottomWall  = new Wall({normal : [0,-1,0], distance : 140, restitution : 0});



    function gridItemTrans() {
         return this.particle.getTransform();
    }

    function addGridRepulsion(){
      var sq1, sq2;
      for (var i = 0; i < gridItems.length; i += 1){
        sq1 = gridItems[i].particle;
        physics.attach([leftWall, rightWall, topWall, bottomWall], sq1);
          if ((i + 1) < gridItems.length){
            for (var j = i + 1; j < gridItems.length; j += 1){
              sq2 = gridItems[j].particle;
              physics.attach(gridR, sq1, sq2);
            }
            }
        }
      }

    function addBodies(){
      gridItems.forEach(function(ele){
        physics.addBody(ele.particle);
      });
    }

    for (var rows = 0; rows < 5; rows += 1){

        for (var cols = 0; cols < 5; cols += 1){

          var gridItem = new Surface({
            properties: {
                backgroundColor: '#23AD23'
            }
            }); 

           gridItem.particle = new Particle({
            position: [positionsArray[rows], positionsArray[cols], 0]
           });

           //physics.addBody(gridItem.particle);
           //physics.attach(centralG, gridItemParticle[rows][cols], planetParticle);

           gridItem.modifier = new Modifier({
            size: [50,50],
            align: [0.5, 0.5],
            origin: [0.5, 0.5],
            transform: gridItemTrans.bind(gridItem)
           });

           context.add(gridItem.modifier).add(gridItem);
           gridItems.push(gridItem);
        }
    }
  addBodies();
  addGridRepulsion();



});

Answer:

To clear up your understanding, we will fist look at the repulsion being applied.

By Default, the Repulsion decay function in Famo.us is a gravity function (an inverse squared distance decay function). Gravity has a decay based on mass and distance.

var gridR = new RepulsionForce({
  strength: 1,
  decayFunction : RepulsionForce.DECAY_FUNCTIONS.GRAVITY
});

You can apply a linear function to your repulsion decay and you will create the affect you are looking for.

var gridR = new RepulsionForce({
  strength: 1,
  decayFunction : RepulsionForce.DECAY_FUNCTIONS.LINEAR
});

If gravity were to decay linearly rather than quadratically, you would need infinite kinetic energy to escape a gravitational field. It would be like living in 2D space.

To answer the second part of your question: The walls have no restitution, but the particles still respond to the force of the other particles.


Related:


Is there a way to define a float array in Python?


python,arrays,numpy,physics,astronomy
For my astronomy homework, I need to simulate the elliptical orbit of a planet around a sun. To do this, I need to use a for loop to repeatedly calculate the motion of the planet. However, every time I try to run the program, I get the following error: RuntimeWarning:...

Throwing an object with SpriteKit


ios,swift,sprite-kit,physics
I have the following code at the moment. Even though the code build is successful, i cannot seem to get it to work. I am trying to make it so when you flick the object, it moves at the velocity of your begin and end touch. import SpriteKit class GameScene:...

on collision events in famo.us: How to get bodies involved?


famo.us
I know how I can listen on collisions: collision.on('collision', function(e){ //e is one element involved in my collision }); But how to I get both bodies involved? Only one body is passed to this function....

Famo.us: why won't the width of the clicked surface change?


famo.us
Famous.Engine = famous.core.Engine; Famous.Surface = famous.core.Surface; Famous.RenderNode = famous.core.RenderNode; Famous.ContainerSurface = famous.surfaces.ContainerSurface; Famous.ScrollView = famous.views.Scrollview; Famous.SequentialLayout = famous.views.SequentialLayout; Famous.Transform = famous.core.Transform; Famous.Transitionable = famous.transitions.Transitionable; Famous.SnapTransition = famous.transitions.SnapTransition; Famous.TransitionableTransform = famous.transitions.TransitionableTransform;...

Famo.us: How to put form fields inside a scrolling view that works on iOS and Safari?


javascript,mobile-safari,famo.us
I’m trying to create a scrolling form for a mobile web app using a Famous ScrollView. However, iOS exhibits severe display bugs when scrolling while the keyboard is active. This occurs whether using an InputSurface or embedding an <input> directly in the Surface HTML. What’s the best way to achieve...

How can I use the (seemingly built in) famo.us device view?


famo.us
In this launch event, Hongxu Liu adds device views to his famous app. Are they open sourced? I cannot find anything about it. I am currently developing a phonegap app, and this would come in handy.

b2Draw subclass member functions not called


c++,box2d,physics
I'm trying to create a minimal test case for another question about Box2d, but I am unable to cause the member functions of my custom drawer to be called: #include <iostream> #include "Box2D/Box2D.h" class DebugDrawer : public b2Draw { public: DebugDrawer() { AppendFlags(b2Draw::e_shapeBit); AppendFlags(b2Draw::e_jointBit); AppendFlags(b2Draw::e_aabbBit); AppendFlags(b2Draw::e_pairBit); AppendFlags(b2Draw::e_centerOfMassBit); } void DrawPolygon(const...

Famo.us how to select the surfaces in a scrollView that were not clicked on?


famo.us
I have a scrollView that contains 5 surfaces. If I click on a surface, I would like the others to be either faded out, z-indexed far behind or translated off the screen. The problem is, I do not know how to implement the selection of the other surfaces. Famo.us Code:...

How can you alter the classList of an element in Famo.us + Angular?


javascript,angularjs,famo.us,famous-angular
I'm using Famo.us + Angular. I'm able to retrieve the classList of a Surface by doing this: $scope.findElement = function() { var elem = $famous.find("#colored-bg")[0].renderNode; // Returns Surface console.log(elem.classList); // RETURNS: ["purple-bg", "container-border", "box-shadow"] }; You can't perform any of the operations on Famo.us object which you normal could to...

non linear least square fitting with the variable as the integration limit


python,physics,numeric,curve-fitting
I'm trying to make some non-linear fittings with python which involve an integral, and the limits of the integral depends on the independent variable. The code is the following: import numpy as np import scipy as sc import matplotlib.pyplot as plt from scipy.optimize import curve_fit from scipy.integrate import quad T,M=np.genfromtxt("zfc.txt",...

Famous Draggable vs. GenericSync with famous-views


meteor,coffeescript,famo.us,famono
I'm working through use of Draggable and GenericSync with famous and meteor famous-views package and not understanding (obviously) I'd like to drag a surface with constraints and perform another action when predetermined limits are reached. I'm learning and from the examples I've found, I haven't been able to get this...

Make ball bounce to a stop


java,physics,bounce
I have a ball class with the following variables: int x,y,width,height; double velX,velY; I want to make it so that whenever the ball hits a block, it bounces and it looses some velocity. //Gravity & movement for the ball ball.setVelY(ball.getVelY() + 0.2); ball.setY((int)(ball.getY() + ball.getVelY())); //Make the ball bounce. if(ball.getBounds().intersects(block.getBounds()){...

Unexpected behaviour in famo.us javascript


javascript,famo.us
The code below creates up the elements for a grid, and arranges it using the transformOut method. This part works fine, but I then want the grid to collapse in to the centre on mousedown, and spring back out again on mouseup. However, all subsequent calls to either the transformIn...

Why does SKLabelNode increment too much on Contact? (Swift)


swift,physics,bitmask
I am trying to have my Label to increment +1 every time a sprite makes contact with a Contact node, but it increments by large numbers like +23. I think what is happening is that its taking into account every millisecond that the sprite is touching the node, but i...

Center Surfaces inside SequentialLayout (famo.us)


famo.us
I am trying to solve the problem of centering Surfaces with different widths inside a vertical SequentialLayout, in famo.us. I've gone through the Famo.us University and the source code on the github site, but couldn't figure out a "clean" solution.. For instance, the following code is adapted from http://famo.us/university/lessons/#/layout/sequential-layout/2 to...

Keep node in view


ios,sprite-kit,physics,game-physics,skphysicsbody
I have a question: Typically, a node will be removed from the view of its position if it exceeds the device's height. I'm using gravity so it falls back down into the view. How would I make it so the node doesn't remove itself from the view?...

Matlab and mechanics (mostly physics)


matlab,physics,simulink
I am trying to solve a mechanics problem regarding momentum of two shafts. I have never had a class an mechanics before, so i don't know how to approach this problem. Given: equations: • J1*dw1/dt + Td(w12)+Ts(phi12) = T1; • J2*dw2/dt - Td(w12) -Ts(phi12) = T2; where w1 = dphi1/dt,...

Simple way to numerically integrate constrained dynamics?


physics,numerical-methods
For example, a simple pendulum (string length = 1) can be described as mx'' = λ*2x my'' = -mg + λ*2y x^2 + y^2 - 1 = 0 where the primes mean derivatives w.r.t time, and λ*2x and λ*2y are the constraint forces coming from the 3rd equation, which is...

Missing Relative Transform in AddPhysicsHandleComponent


physics,game-physics,unreal-engine4
I'm trying to rebuild the tutorial "Pick Up Physics Object Tutorial" and I need to use "Relative Transform" in "AddPhysicsHandleComponent" but it is not there. On this site https://docs.unrealengine.com/latest/INT/BlueprintAPI/AddComponent/Physics/AddPhysicsHandleComponent/index.html the AddPhysicsHandleComponent is shown exactly the way I need it but in Unreal Engine itself it appears without the "Relative Transform"....

Use famo.us with meteor without famous-views


meteor,famo.us
I would like to use famo.us in my meteor application. I would like to write pure famo.us javascript without the famous-views package. Now, I have a question: Is it possible to use with blaze? Can I create for example content in a surface with reactive data by using {{data}}?

How to properly layout in Famo.us/ famous-views?


meteor,famo.us
I am using meteor.js and the gadicohen:famous-views and mjn:famous packages. I would like to list projects to be displayed in the layout pattern above. The first project is twice the height of the subsequent two, and takes half of the screen. The subsequent two split the height of the...

Famo.us physics engine: forces and walls not behaving as expected


physics,famo.us
I am tyring to create a grid of particles, using the famous physics engine. I thought that if 25 particles were placed beteween 4 bounding walls (forming a square) and they all had an equal repulsion force to each other, they would naturally form a grid - ie. they would...

Physics based 2D movement: Changing direction of an object over time


java,math,2d,physics,trigonometry
I am currently creating a 2D space game in Java, in which you control a ship in, well, space. The game does not use any external libraries. The ship is supposed to move towards the cursor. However, when moving the cursor, the old force does not magically disappear; the ship...

How to install the IOP (Institute of Physics) Latex document class for Texlive and the Lyx Document Processor (Answer Provided)


latex,document,physics,lyx,latex-environment
Background I originally asked a question on Stackoverflow, asking how I add the IOP document class to the list of available document classes in Lyx. (I will try to remove or merge that out dated quesiton.) I now understand that this is a 2-stage process. Stage 1 is to install...

OBDII - determine gear given speed and RPM


physics,obd-ii
I'm developing an Android application where we use the OBDII to read car's engine parameters. Currently we are obtaining speed (kmh), engine's RPM and mass airflow live while driving the car. We now have to find a way how using these parameters we are able to obtain from OBDII determine...

Another effect to slide views on fame.us app?


famo.us
i have 2 views in fame.us app, and slide in EdgeSwapper view, and i want change default effect of EdgeSwapper.show(). I want effect like a smooth transition forward and backwards, how i can do it?

Make two physics objects not collide but do detect collisions in Unity


unity3d,2d,physics
I have a Unity project in which there is a 2D game world that consists of static colliders to make the geometry solid to the characters that inhabit it. The player is a dynamic collider (with a non-kinematic rigidbody). There's also an enemy character that is also a dynamic collider....

MATLAB and mechanics (physics mostly) [part II]


matlab,physics,simulink
Resume form part 1 Basic scheme representing the system: We assume that coupling of the two shafts is done with a clutch Equations: • J1*dw1/dt + Td(w12)+Ts(phi12) = T1; • J2*dw2/dt - Td(w12) -Ts(phi12) = T2; where w1 = dphi1/dt, w2 = dphi2/dt, phi12 = phi1 - phi2 w12 =...

N body simulation in C#


c#,algorithm,simulation,physics,numerical-methods
I'm trying to implement an N body simulation in C# using either Runge Kutta 4 or Velocity Verlet integration algorithms. Before I move to a bigger number of particles, I wanted to test the simulation by modeling the earth's orbit around the sun, however, instead of the elliptical orbit, I...

Distribute circles around a center circle


javascript,geometry,computational-geometry,famo.us
I'm trying to place six circles around a center circle. Eeach of them has the same diameter so it should be possible to place them around the center without space between or overlaps. I thinking to be close to the solution but there are small overlaps. I can't find an...

piping event handlers in famo.us


famo.us
I want to pipe event handler of view1 to event handler of view2. As a result the following code should trigger eventListeners of both: view1 and view2: define(function(require, exports, module) { var Engine = require('famous/core/Engine'); var View = require('famous/core/View'); var Surface = require('famous/core/Surface'); var ctx = Engine.createContext(); var surf =...

Famo.us View can't contain imagesurface on top of a surface inside a scrollview


javascript,famo.us
define(function(require, exports, module){ var View = require('src/core/View'); var Surface = require('src/core/Surface'); var ImageSurface = require('src/surfaces/ImageSurface'); var EventHandler = require('src/core/EventHandler'); var StateModifier = require('src/modifiers/StateModifier'); var RenderNode = require('src/core/RenderNode'); var Transform = require('src/core/Transform') function DetailedList(){ View.apply(this, arguments); _createStrips.call(this); _createImage.call(this); } DetailedList.prototype =...

How to animate famo.us surface in Meteor


meteor,famo.us
I am using the famous-views package for Meteor, and I love it. I have created a simple UI with a few templates and a few surfaces and so on. Now I would like to do some simple animations. I would like to do something like this: surface.on("click", function (e) {...

Cannot assign a value of type “Game Scene” to a value of type “SKPhysicsContactDelegate”


swift,collision-detection,physics,collision,contact
I am trying to build flappy bird on my own. Everything works fine but now I have added the CategoryBitMasks and all that stuff and every time I try adding this piece of code: self.physicsworld.contactDelegate = self I get the error message : Cannot assign a value of type 'GameScene'...

Python pendulum


python,physics,equation,angle
I'm trying to deduce the pendulum equation out of the Verlet algorithm. This is what I've done with phython using "r" as the angle of the pendulum, "w" as the speed and "a" as the angular acceleration. "h" is the increase of time, and my main problem is that if...

Exclude input events in famous-angular from general Event


famo.us,famous-angular
I'm writing a mobile app with famous/angular. A swipe to the right in any view reveals the menu. For this I have set up the following event handling: var MouseSync = $famous["famous/inputs/MouseSync"]; var TouchSync = $famous["famous/inputs/TouchSync"]; var GenericSync = $famous['famous/inputs/GenericSync']; $scope.sync = new GenericSync( ["mouse", "touch"], {direction: GenericSync.DIRECTION_X} ); $scope.sync.on('update',...

Famo.us ScrollContainer not scrolling


javascript,famo.us
define(function(require, exports, module){ var View = require('src/core/View'); var Surface = require('src/core/Surface'); var ScrollContainer = require('src/views/ScrollContainer'); function ListView(){ View.apply(this, arguments); _createContent.call(this); } ListView.prototype = Object.create(View.prototype); ListView.prototype.constructor = ListView; ListView.DEFAULT_OPTIONS = { data: [] } function _createContent(){ var sc = new ScrollContainer(); var sequence = []; sc.sequenceFrom(sequence); for (var i = 0;...

Swift - Good random node generation SpriteKit


swift,random,sprite-kit,physics
i try to creating a game where you need to avoid objects (nodes), and I wan't to generate these node at a random position (out of the screen, on the right) and with an action, the nodes cross the screen to the left. But how can I create a good...

famous: can't draw image to CanvasSurface with own size property


javascript,css,canvas,famo.us
I am new to famo.us and cloned the start example. What I was trying to do, is to create a CanvasSurface, create an Image, load ImageData into it, then draw() the Image onto the canvas' context. The strange thing is, that it works once, when not defining a custom size....

Why do(es) the ball(s) stick to the ground after an arbitrary amount of time?


javascript,html,css,canvas,physics
I have the following code which bounces multiple balls along the screen, making use of physics, and the gravity of jupiter divided by 10 for testing purposes. var canvas = document.getElementById("canvas"), ctx = canvas.getContext('2d'); //jupiter's gravity divided by 10 for testing purposes g = 24.79/10; canvas.width = window.innerWidth - 50;...

SKPhysicsBody avoid collision Swift/SpriteKit


swift,sprite-kit,physics
I have 3 SKSpriteNodes in my Scene. One bird, one coin and a border around the scene. I don't want the coin and the bird to collide with each other but withe the border. I assign a different collisionBitMask and categoryBitMask to every node: enum CollisionType:UInt32{ case Bird = 1...

How do I make a decaying oscilating function in python?


python,numpy,matplotlib,graph,physics
I have a code in python to represent the energy decay in a damped oscilator, it reads like this: def E(wt, Q): return (np.e**(-x/Q))*(1-(1/2*Q)*np.sin(2*x)) x = np.linspace(0,20,1000) y0 = E(x,2) y1 = E(x,4) y2 = E(x,8) y3 = E(x,16) plt.plot(x, y0, 'p', label=r'$Q=2$') plt.plot(x, y1, 'r', label=r'$Q=4$') plt.plot(x, y2, 'g',...

Trying to make a simple falling ball program


java,physics,particle
This is what I have so far. It tells me that I have a syntax error on the lines marked below, saying that it expected a "{" and a "}" respectively, without the double quotes around them. Any suggestions? public class attempt1 { //use Euler-Richardson algorithm //defining the initial conditions...

Object 'breaks' from falling


objective-c,ios8,sprite-kit,physics
I've made a square with x=25 & y= 25 and attached an SKPhysicsBody. I've made a standard platform level that has several tall drop areas. I want the the square to 'break'/suffer damage from falling from tall places. I looked at wikipedia and found Newton's law of universal gravitation F=mg....

Is it possible to have multi touch input linked across multiple surfaces in famo.us ?


javascript,graphics,touch,famo.us
I have created the following render tree: Context -> MainNode -> ImageSurfaces -> MoreSurfaces The image surfaces can be added by the user and are created dynamically, I want to have drag for each ImageSurface depending upon the touch input given by the user. For eg. If I have two...

What is famous-gl ?


javascript,famo.us
In a lot of of codepen samples of Famo.us I see people including famous-gl references for rendering things, but I cannot find which library is to be referenced to use it nor I can find any documentation on it can someone guide me in the correct direction ?

How to get Famo.us draggable modifier's render node


draggable,famo.us
I am trying to get parent renderNode of a draggable modifier on 'end' event, is there any api to get a renderNode to which draggable belongs to? My code is as follows : /*globals define*/ define(function(require, exports, module) { var View = require('famous/core/View'); var Surface = require('famous/core/Surface'); var Transform =...

How to simulate air resistance for a pendulum?


java,math,physics
I use the following code to simulate the animation of a pendulum, however, it ignores air resistance and never stops. while (true) { angleAccel = -9.81 / length * Math.sin(angle); angleVelocity += angleAccel * dt; angle += angleVelocity * dt; repaint(); try { Thread.sleep(15); } catch (InterruptedException ex) {} }...

Famous physics, Uncaught TypeError


javascript,famo.us
The code below generates this error: Uncaught TypeError: Cannot read property '5' of undefined This is thrown by line 52 of the code below. I don't understand how the value of rows or cols gets to 5, when the two loops are set to stop at 4. Thanks for any...