physics, , physics engine: forces and walls not behaving as expected physics engine: forces and walls not behaving as expected


Tag: physics,

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:

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

  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(){

    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.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)




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

By Default, the Repulsion decay function in 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.


Center Surfaces inside SequentialLayout (
I am trying to solve the problem of centering Surfaces with different widths inside a vertical SequentialLayout, in I've gone through the 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 to... why won't the width of the clicked surface change?
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;...

SKPhysicsBody avoid collision Swift/SpriteKit

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...

Famous Draggable vs. GenericSync with famous-views

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...

Simple way to numerically integrate constrained dynamics?

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...

MATLAB and mechanics (physics mostly) [part II]

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 =...

Python pendulum

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,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',...

How to animate surface in Meteor

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) {...

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

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...

Throwing an object with SpriteKit

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:...

Another effect to slide views on app?
i have 2 views in app, and slide in EdgeSwapper view, and i want change default effect of I want effect like a smooth transition forward and backwards, how i can do it?

What is famous-gl ?

In a lot of of codepen samples of 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 ? physics engine: forces and walls not behaving as expected

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...

OBDII - determine gear given speed and RPM

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...

Distribute circles around a center circle

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... How to put form fields inside a scrolling view that works on iOS and Safari?

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...

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

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...

on collision events in How to get bodies involved?
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....

How to get draggable modifier's render node

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 =...

Keep node in view

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?...

Object 'breaks' from falling

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....

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

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;...

Missing Relative Transform in AddPhysicsHandleComponent

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 the AddPhysicsHandleComponent is shown exactly the way I need it but in Unreal Engine itself it appears without the "Relative Transform"....

piping event handlers in
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 =...

Unexpected behaviour in javascript

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... how to select the surfaces in a scrollView that were not clicked on?
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. Code:...

Use with meteor without famous-views

I would like to use in my meteor application. I would like to write pure 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}}?

Famous physics, Uncaught TypeError

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...

How to properly layout in famous-views?

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...

How to simulate air resistance for a pendulum?

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) {} }...

Swift - Good random node generation SpriteKit

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... View can't contain imagesurface on top of a surface inside a scrollview

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);;; } DetailedList.prototype =...

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

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....

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

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...

b2Draw subclass member functions not called

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...

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

I am new to 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....

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

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:...

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

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...

Matlab and mechanics (mostly physics)

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,...

Trying to make a simple falling ball program

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...

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

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",... ScrollContainer not scrolling

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);; } 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;...

How can I use the (seemingly built in) device view?
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.

N body simulation in C#

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...

Make ball bounce to a stop

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()){...

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

I'm using + 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 object which you normal could to...

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

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'...

How do I make a decaying oscilating function in python?

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',...