GithubHelp home page GithubHelp logo

n5ro / aframe-physics-system Goto Github PK

View Code? Open in Web Editor NEW
504.0 30.0 137.0 1.29 MB

Physics system for A-Frame VR, built on CANNON.js.

Home Page: https://n5ro.github.io/aframe-physics-system/

License: MIT License

JavaScript 100.00%
aframe physics webvr threejs

aframe-physics-system's Introduction


a-frame-physics-system is now maintained at: c-frame/aframe-physics-system

Available on npm as @c-frame/aframe-physics-system


Physics for A-Frame VR

Latest NPM release GitHub license Build Test

Components for A-Frame physics integration. Supports CANNON.js and Ammo.js

New Features

Ammo.js driver support has been added. Please see Ammo Driver for documentation. CANNON.js support may be deprecated in the future.

Contents

Installation

Scripts

In the dist/ folder, download the full or minified build. Include the script on your page, and all components are automatically registered for you:

<script src="https://cdn.jsdelivr.net/gh/n5ro/aframe-physics-system@v$npm_package_version/dist/aframe-physics-system.min.js"></script>

CDN builds for aframe-physics-system@v$npm_package_version:

npm

npm install --save aframe-physics-system
// my-app.js
require('aframe-physics-system');

Once installed, you'll need to compile your JavaScript using something like Browserify or Webpack. Example:

npm install -g browserify
browserify my-app.js -o bundle.js

bundle.js may then be included in your page. See here for a better introduction to Browserify.

npm + webpack

When using webpack, you need to ensure that your loader for .js files includes this dependency. The example below assumes you're using Babel.

{
  test: /\.js$/,
  include: ['src', require.resolve('aframe-physics-system') ],
  use: {
    loader: 'babel-loader', // or whatever loader you're using to parse modules
    options: {}
  }
}

Note: You cannot use exclude: /node_modules for your .js loader. You must instead use include and pass an array of directories as dependencies to transpile.

Basics

<!-- The debug:true option creates a wireframe around each physics body. If you don't see a wireframe,
     the physics system may be unable to parse your model without a shape:box or shape:hull option. -->
<a-scene physics="debug: true">

  <!-- Camera -->
  <a-entity camera look-controls></a-entity>

  <!-- Floor -->
  <a-plane static-body></a-plane>

  <!-- Immovable box -->
  <a-box static-body position="0 0.5 -5" width="3" height="1" depth="1"></a-box>

  <!-- Dynamic box -->
  <a-box dynamic-body position="5 0.5 0" width="1" height="1" depth="1"></a-box>

</a-scene>

Components

dynamic-body and static-body

The dynamic-body and static-body components may be added to any <a-entity/> that contains a mesh. Generally, each scene will have at least one static-body for the ground, and one or more dynamic-body instances that the player can interact with.

  • dynamic-body: A freely-moving object. Dynamic bodies have mass, collide with other objects, bounce or slow during collisions, and fall if gravity is enabled.
  • static-body: A fixed-position or animated object. Other objects may collide with static bodies, but static bodies themselves are unaffected by gravity and collisions.
Property Dependencies Default Description
shape auto auto, box, cylinder, sphere, hull, none
mass dynamic-body 5 Simulated mass of the object, > 0.
linearDamping dynamic-body 0.01 Resistance to movement.
angularDamping dynamic-body 0.01 Resistance to rotation.
sphereRadius shape:sphere Override default radius of bounding sphere.
cylinderAxis shape:cylinder Override default axis of bounding cylinder.

Body Shapes

Body components will attempt to find an appropriate CANNON.js shape to fit your model. When defining an object you may choose a shape or leave the default, auto. Select a shape carefully, as there are performance implications with different choices:

  • None (none) – Does not add collision geometry. Use this when adding collision shapes manually, through the shape component or custom JavaScript.
  • Auto (auto) – Chooses automatically from the available shapes.
  • Box (box) – Great performance, compared to Hull or Trimesh shapes, and may be fitted to custom models.
  • Cylinder (cylinder) – See box. Adds cylinderAxis option.
  • Sphere (sphere) – See box. Adds sphereRadius option.
  • Convex (hull) – Wraps a model like shrink-wrap. Convex shapes are more performant and better supported than Trimesh, but may still have some performance impact when used as dynamic objects.
  • Primitives – Plane/Cylinder/Sphere. Used automatically with the corresponding A-Frame primitives.
  • Trimesh (mesh) – Deprecated. Trimeshes adapt to fit custom geometry (e.g. a .OBJ or .DAE file), but have very minimal support. Arbitrary trimesh shapes are difficult to model in any JS physics engine, will "fall through" certain other shapes, and have serious performance limitations.

For more details, see the CANNON.js collision matrix.

Example using a bounding box for a custom model:

<!-- Box -->
<a-entity obj-model="obj: url(...)" dynamic-body="shape: box; mass: 2"></a-entity>

<!-- Cylinder -->
<a-entity obj-model="obj: url(...)" dynamic-body="shape: cylinder; cylinderAxis: y; mass: 5"></a-entity>

shape

Compound shapes require a bit of work to set up, but allow you to use multiple primitives to define a physics shape around custom models. These will generally perform better, and behave more accurately, than mesh or hull shapes. For example, a chair might be modeled as a cylinder-shaped seat, on four long cylindrical legs.

Example:

<a-entity gltf-model="src: mug.glb"
          body="type: dynamic; mass: 5; shape: none;"
          shape__main="shape: cylinder;
                       height: 0.36;
                       radiusTop: 0.24;
                       radiusBottom: 0.24;"
          shape__handle="shape: box;
                         halfExtents: 0.15 0.18 0.04;
                         offset: 0.4 0 0;">
</a-entity>
Property Shapes Default Description
shape box box, sphere, or cylinder
offset 0 0 0 Position of shape relative to body.
orientation 0 0 0 1 Rotation of shape relative to body.
radius sphere 1 Sphere radius.
halfExtents box 1 1 1 Box half-extents. Use 0.5 0.5 0.5 for a 1x1x1 box.
radiusTop cylinder 1 Cylinder upper radius.
radiusBottom cylinder 1 Cylinder lower radius.
height cylinder 1 Cylinder height.
numSegments cylinder 8 Cylinder subdivisions.

constraint

The constraint component is used to bind physics bodies together using hinges, fixed distances, or fixed attachment points.

Example:

<a-box id="other-box" dynamic-body />
<a-box constraint="target: #other-box;" dynamic-body />
Property Dependencies Default Description
type lock Type of constraint. Options: lock, distance, hinge, coneTwist, pointToPoint.
target Selector for a single entity to which current entity should be bound.
maxForce 1e6 Maximum force that may be exerted to enforce this constraint.
collideConnected true If true, connected bodies may collide with one another.
wakeUpBodies true If true, sleeping bodies are woken up by this constraint.
distance type:distance auto Distance at which bodies should be fixed. Default, or 0, for current distance.
pivot type: pointToPoint, coneTwist, hinge 0 0 0 Offset of the hinge or point-to-point constraint, defined locally in this element's body.
targetPivot type: pointToPoint, coneTwist, hinge 0 0 0 Offset of the hinge or point-to-point constraint, defined locally in the target's body.
axis type: coneTwist, hinge 0 0 1 An axis that each body can rotate around, defined locally to this element's body.
targetAxis type: coneTwist, hinge 0 0 1 An axis that each body can rotate around, defined locally to the target's body.

spring

The spring component connects two bodies, and applies forces as the bodies become farther apart.

Example:

<a-box id="anchor" position="0 2 -3" static-body></a-box>
<a-box position="0 1 -3"
       dynamic-body
       spring="target: #anchor;
               damping: 0.25;
               stiffness: 25;"></a-box>
Property Default Description
target Target (other) body for the constraint.
restLength 1 Length of the spring, when no force acts upon it.
stiffness 100 How much will the spring suppress force.
damping 1 Stretch factor of the spring.
localAnchorA Where to hook the spring to body A, in local body coordinates.
localAnchorB Where to hook the spring to body B, in local body coordinates.

Using the CANNON.js API

For more advanced physics, use the CANNON.js API with custom JavaScript and A-Frame components. The CANNON.js documentation and source code offer good resources for learning to work with physics in JavaScript.

In A-Frame, each entity's CANNON.Body instance is exposed on the el.body property. To apply a quick push to an object, you might do the following:

<a-scene>
  <a-entity id="nyan" dynamic-body="shape: hull" obj-model="obj: url(nyan-cat.obj)"></a-entity>
  <a-plane static-body></a-plane>
</a-scene>
var el = sceneEl.querySelector('#nyan');
el.body.applyImpulse(
  /* impulse */        new CANNON.Vec3(0, 1, -1),
  /* world position */ new CANNON.Vec3().copy(el.getComputedAttribute('position'))
);

Events

event description
body-loaded Fired when physics body (el.body) has been created.
collide Fired when two objects collide. Touching objects may fire collide events frequently. Unavailable with driver: worker.

Collisions

NOTE: Collision events are currently only supported with the local driver, and will not be fired with physics="driver: worker" enabled.

CANNON.js generates events when a collision is detected, which are propagated onto the associated A-Frame entity. Example:

var playerEl = document.querySelector('[camera]');
playerEl.addEventListener('collide', function (e) {
  console.log('Player has collided with body #' + e.detail.body.id);

  e.detail.target.el;  // Original entity (playerEl).
  e.detail.body.el;    // Other entity, which playerEl touched.
  e.detail.contact;    // Stats about the collision (CANNON.ContactEquation).
  e.detail.contact.ni; // Normal (direction) of the collision (CANNON.Vec3).
});

Note that CANNON.js cannot perfectly detect collisions with very fast-moving bodies. Doing so requires Continuous Collision Detection, which can be both slow and difficult to implement. If this is an issue for your scene, consider (1) slowing objects down, (2) detecting collisions manually (collisions with the floor are easy – position.y - height / 2 <= 0), or (3) attempting a PR to CANNON.js. See: Collision with fast bodies.

System Configuration

Contact materials define what happens when two objects meet, including physical properties such as friction and restitution (bounciness). The default, scene-wide contact materials may be configured on the scene element:

<a-scene physics="friction: 0.1; restitution: 0.5">
  <!-- ... -->
</a-scene>

NOTE: It is possible to run physics on a Web Worker using the physics="driver: worker" option. Using a worker is helpful for maintaining a smooth framerate, because physics simulation does not block the main thread. However, scenes needing highly-responsive interaction (for example, tossing and catching objects) may prefer to run physics locally, where feedback from the physics system will be immediate.

Property Default Description
debug true Whether to show wireframes for debugging.
gravity -9.8 Force of gravity (in m/s^2).
iterations 10 The number of solver iterations determines quality of the constraints in the world. The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.
maxInterval 0.0667 Maximum simulated time (in milliseconds) that may be taken by the physics engine per frame. Effectively prevents weird "jumps" when the player returns to the scene after a few minutes, at the expense of pausing physics during this time.
friction 0.01 Coefficient of friction.
restitution 0.3 Coefficient of restitution (bounciness).
contactEquationStiffness 1e8 Stiffness of the produced contact equations.
contactEquationRelaxation 3 Relaxation time of the produced contact equations.
frictionEquationStiffness 1e8 Stiffness of the produced friction equations.
frictionEquationRegularization 3 Relaxation time of the produced friction equations
driver local [local, worker]
workerFps 60 Steps per second to be used in physics simulation on worker.
workerInterpolate true Whether the main thread should interpolate physics frames from the worker.
workerInterpBufferSize 2 Number of physics frames to be 'padded' before displaying. Advanced.
workerDebug false If true, the worker codepaths are used on the main thread. This is slow, because physics snapshots are needlessly serialized, but helpful for debugging.

More advanced configuration, including specifying different collision behaviors for different objects, is available through the CANNON.js JavaScript API.

Resources:

Examples

To help demonstrate the features and capabilities of aframe-physics-system a collection of examples have been prepared. Please see Examples for a summary and link to each of the prepared examples.

aframe-physics-system's People

Contributors

3datawill avatar arpu avatar avgp avatar brodavi avatar dependabot[bot] avatar diarmidmackenzie avatar donmccurdy avatar donmccurdy-up-for-adoption avatar galadirith avatar garrensweet avatar gftruj avatar infinitelee avatar jesstelford avatar jfaust avatar kylebakerio avatar mignonbelongie avatar mqp avatar n5ro avatar propuke avatar wmurphyrd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aframe-physics-system's Issues

dynamic-body fails on custom object (.obj)

Hi, I've been trying to fix this myself but no luck.

When I include this:
<a-entity hoverable grabbable stretchable drag-droppable obj-model="obj: #my-obj; mtl: #my-mtl" scale="1 1 1" position="1 3 -5" class="thing" dynamic-body="shape: box"></a-entity>
My .obj model hangs in mid-air, with no bounding box.

If I use shape: auto, the object drops through the floor, which is:
<a-plane static-body rotation="-90 0 0" width="30" height="30" color="grey"></a-plane>

hoverable grabbable stretchable drag-droppable is from https://github.com/wmurphyrd/aframe-super-hands-component. I have physics debug on.

Thanks!

problems in chrome

the example doesn't seem to work in latest webVR chrome Version 56.0.2902.0 (64-bit)

i briefly see dynamic bodies before sim starts then they just disappear and all of the positions and rotations end up as NaN

things work as expected in firefox nightly and it works in release chrome without VR Version 55.0.2883.87 m (64-bit)

perhaps related to bad time values in this release of webVR chrome aframevr/aframe#2207

Constraints error when touching target

Hello,
I'm trying to use a basic lock constraint between two objects, where object "blue" references object "red" as follows:
<a-entity class="model" id="red" mixin="cube" material="color: red" position="0 1 -1" collision-filter="group: red; collidesWith: default, red"></a-entity>
<a-entity class="model" id="blue" mixin="cube" material="color: blue" position="0 1.6 -1" collision-filter="group: red; collidesWith: default, red" constraint="target: #red"></a-entity>
The basic function of this constraint work all right; when I pick up and move the red cube, the blue one follows. However, if my controller's collider even slightly touches the blue box, this error is thrown and the program crashes.
19357687_10212764969181164_944718763_n
I hope you could take a look at this.
Thanks!

Edit: Also, placing a collada model as the target of a constraint doesn't seem to work. My two entities are defined as:
<a-entity id="hulldae" class="model" collada-model="#hulldae" position="1 1 1" collision-filter="group: red; collidesWith: default, red" stuck dynamic-body="shape: box; linearDamping: 0.99; angularDamping: 0.99"></a-entity>
<a-entity id="mol" class="model" obj-model="obj: #model1; mtl: #mat1" position= "-0.5 1 1" collision-filter="group: red; collidesWith: default, red" dynamic-body="shape: box; linearDamping: 0.99; angularDamping: 0.99" constraint="target: #hulldae"></a-entity>
However, if I place the constraint="target: #hulldae" on the #mol, there is no constraint action, whereas if I place constraint="target: #mol on the #hulldae, they move together as expected.

Links to the models:
hulldae: https://skfb.ly/68AsK
mol: https://skfb.ly/6rYOZ

The error remains if I turn both into collada objects; it only seems to lock correctly for .obj ones. I do want to use collada objects though, as .obj collisions aren't as good.

Thanks! :)

Collisions -- how do I tell what faces of each colliding body intersected?

Hi,

I've created a static-body entity and set up an event handler to let me know when the player collides with it. I'm trying to find out which face of the body the player collided with, so I logged event.detail for the collision event, but it wasn't clear to me that that information was anywhere in the detail property. I checked event.detail.contact, and nothing stood out to me as anything that would represent the face of the body where the two objects intersected.

I'm new to aframe, so it's possible I missed this.

Thank you for all your awesome work!

Example is broken (Type errors) in A-Frame 0.5.0

The example does not work in in A-Frame 0.5.0 - both current Firefox and Chrome (Mac) throw TypeError.

Chrome:

Uncaught TypeError: Cannot read property 'position' of undefined
    at i.<anonymous> ((index):51)

Firefox:

TypeError: box.body is undefined[Learn More] examples:51:1

Physics breaks with nested a-entities and rotations

The physics system seems to break (everything appears in the wrong place) if placed inside a parent a-entity that has a translation/rotation. For example:

<a-scene physics>
	<a-entity position="3 0 0">
		<a-plane color="green" static-body height="3" width="3" rotation="-90 0 0" position="0 0 -5"></a-plane>
		<a-box color="red" dynamic-body position="0 5 -5"></a-box>
	</a-entity>
</a-scene>

Here you will see the red box will fall and miss the green floor completely. But if you change the parent a-entity position to "0 0 0" then it lands as expected.

At a guess, this may be a similar problem to one I lodged a PR request against for sphere-collider: c-frame/aframe-extras@6f5627e (basically you are calling getWorldPosition for one set of co-ordinates but not the other)

It's fine if the rotation exists but is "0 0 0", so it's not the nesting per se that upsets it.

Inconsistent results from static-body collisions

I'm facing a issue when trying to create collision geometries with static-body flag.
I have created a custom loader component to update the loading screen progress bar.

However when using it, the results from static-body are inconsistent. Sometimes on page load both object don't have collisions, sometimes one has and sometimes both do. This is most likely something to do with the loading order of objects.

<!-- Geometry -->
<a-entity objloader='file: ceilingBaked' 
		  position="0 0 0"
		  static-body="shape: auto"></a-entity>
<a-entity objloader='file: interiorBaked' 
		  position="0 0 0"
		  static-body="shape: auto"></a-entity>
init: function () {

	thisElement = this.el.object3D;
	var objName = this.data.file;

	// Loader //
	loader = new THREE.OBJLoader(manager);

	loader.load( "geo/" + objName + ".obj", function ( object ) {

		var material = new THREE.MeshBasicMaterial();
		loader = new THREE.TextureLoader(manager);

		object.traverse( function ( child ) {
			if (child instanceof THREE.Mesh) {
				child.material = material;
				child.material.map = loader.load( "img/" + objName + '_nonCompressed' + ".jpg" );
				addGeo = child;
			}	
		} );
    } );
}

The whole page is here:
https://toseben.github.io/interactive_webViz/aframe_defineComponent.html

I already fixed the issue by approaching the loading differently, by using with a custom shader instead.
https://toseben.github.io/interactive_webViz/aframe_collision.html

collide event seems to be not firing

Hi, I'm trying to listen for the collide event,
simply by entityWithADynamicBody.addEventListener('collide',(e)=>{});

It seems to be correct, moreover it works on earlier versions (1.4.1 at least), as presented in my fiddle.

But when i link the newest version ([2.0.0](<script src="//cdn.rawgit.com/donmccurdy/aframe-physics-system/v2.0.0/dist/aframe-physics-system.min.js"></script>)), it doesn't fire at all, as presented in my fiddle.

Am I missing something here ?
a-frame version: 0.6.1.

Kinematic Body?

Was trying to figure out how to get the player camera to act as a rigid body but ended up having to use aframe-extras lib for this as it doesn't seem like this was ported over to the new physics system. Please let me know if I missed something.

Problem with convex hull creation

Hello,
I'm trying to use a convex hull collider for my .obj model (which you can view here), but was running into issues with assigning the collider, where the wireframe would highlight only a small section of the whole model, and even that section would pass through my other objects (simple cubes with box colliders). So I then switched to a simpler model to see if it worked.
I load the .obj models (and .mtls if they have them) as a-asset-items, and then create a-entities as follows: <a-entity id="hull" class="model" obj-model="obj: #hull" position="-0.5 1 1" collision-filter="group: red; collidesWith: default, red" stuck dynamic-body="shape: hull; linearDamping: 0.99; angularDamping: 0.99" material="color: red"></a-entity>. However, for both the complex model and this simpler one, I get the error below. I even tried giving primitive cubes a hull collider and got this same error.
capture
Upon investigating the code in aframe-extras.js, it looks like the problem occurs when getGeometry() is called, where getGeometry calls getMeshes(), and the meshes that are pushed actually do not even have any vertices component.
So then I thought maybe it's caused by the object not being loaded completely, so I tried adding an event listener for 'body-loaded' that would add the dynamic-body component afterwards. When I tried this, it looks like the object is given a dynamic-body with a box shape by default, and this doesn't get overridden by the "setAttribute" that I call later.
So I thought perhaps the problem could be in the way the .obj models are loaded on aframe, and decided to try using .dae models instead. However, that threw a different error, shown below:
capture1
This error keeps popping up in the console endlessly, with the number in the [brackets] incrementing each call.
I hope you can help me out with this :)
Thanks!

how to programatically add entity with dynamic body?

working on a bow and arrow and running into some issues trying to dynamically add the arrow to the scene and make it fly.

what's the proper way to make sure that the arrow's dynamic body is available to apply an impulse?

i get an entity.body is undefined error if i do it this way

    var matrixWorld = bow.object3D.matrixWorld;
    var shotDirection = new THREE.Vector3();
    shotDirection.setFromMatrixPosition(matrixWorld);

    var entity = document.createElement('a-entity');
    entity.className = "arrow"
    entity.setAttribute('obj-model', 'obj: #arrow-obj; mtl: #arrow-mtl')
    entity.setAttribute('scale', '0.05 0.05 0.05 ');
    entity.setAttribute('dynamic-body', 'shape:auto');
    scene.appendChild(entity);

    entity.addEventListener('loaded', function() {
      var shotPosition = entity.getAttribute('position');
      entity.body.applyImpulse(
        /* impulse */
        new CANNON.Vec3.copy(shotDirection),
        /* world position */
        new CANNON.Vec3().copy(shotPosition)
      );

    });

is there another technique i should be using? a pool or something?

thanks!!

Glitchy object position.

When I add a lot of objects to a scene, the models start twitching within their bounding boxes, as seen here...

twitch

The syntax for these models is as follows...
<a-entity scale=".5 .5 .5" obj-model="obj: #sketch-obj; mtl: #sketch-mtl" dynamic-body="shape: box; mass: 2"></a-entity>

You can try it here, click the mouse button to add objects.
http://flukeout.github.io/test/

Any info or advice is helpful!

Unable to make impulse on new child

Hi,

I am trying to create a bullet attracted by the gravity but I am facing a little problem. I am not sure if it comes from a bug within the physics system or if I am just doing it wrong.

The idea would be that, a gun, when triggered, create a a-sphere with an impulse applied so the sphere goes on the same vector than where the gun is heading (red line show what is happening right now, green light show what should happen) but the sphere doesn't appear.

Here is code appending the sphere to the gun and applying the impulse:

CURSOR.addEventListener("click", function(evt){
        var matrixWorld = GUN.object3D.matrixWorld;
        var shotDirection = new THREE.Vector3();
        shotDirection.setFromMatrixPosition(matrixWorld);

        var bullet = document.createElement("a-sphere");
        bullet.setAttribute("color","blue"); 
        bullet.setAttribute("radius","0.03");
        bullet.setAttribute("dynamic-body","shape: sphere;");
        bullet.addEventListener("body-loaded", function(evt) {
          bullet.body.applyImpulse(
            /* impulse */        new CANNON.Vec3().copy(shotDirection),
            /* world position */ new CANNON.Vec3().copy(GUN.getAttribute("position"))
          );
        });
        GUN.appendChild(bullet);
      })

As said earlier and because I do not see errors in the dev console, I am definitively not sure if this a problem from my side or within the physic system so I thought filling an issue would be the most logic to do.

Thanks in advance!

Player colision with wavefront(obj)

I have implanted a mapping with multiple walls in obj. But in no way do I get any collisions detected. Does it work in obj with multiple vertices?

Support physics in a Web Worker

Ok so, the plan.

Body and World objects will be replaced with stubs or proxies. Modifications to either are recorded and sent (batched) to a remote driver. The driver pushes back, asynchronously, data about the state of all current bodies, and intersections.

Client operations:

  • body.applyImpulse()
  • body.applyForce()
  • world.add/removeConstraint()
  • world.add/removeBody()

Most/all property modifications should also be persisted.

Drivers:

  • LocalPhysicsDriver.js
  • WorkerPhysicsDriver.js
  • Client / ServerPhysicsDriver.js (someday)

Serialization:

Driver will, at each tick, provide a description of scene state. Rough sketch:

{
  type: 'step',
  bodies: [ ... array of object IDs, lengths ],
  collisions: [ ... ? ... ],
  data: [ ... arraybuffer of positions/velocities/angularVelocities ... ]
}

Data, as an arraybuffer, may be passed back to avoid copying data. This might be a very premature optimization.

Distributed files:

  • aframe-physics-system.full.js (aframe lib + local driver)
  • aframe-physics-system.js + worker-physics-driver.js
  • aframe-physics-system.js + client-physics-driver.js / server-physics-driver.js

Open questions:

  • Serializing state of a Cannon.Body isn't hard, but serializing the initialization data (shapes, potentially nested) kind of seems painful. Can users still call addBody themselves? What's the most precise way to represent geometry?
  • How to make collisions (events, or just the list) available to the aframe client?

make example showing laser-controls and/or cursor

from desktop now you sort of need to use kinematic-body to test physics much; would be much nicer to have something that works with desktop and daydream (and ofc roomscale) without depending on kinematic-body.

Possible debug UI wireframe issue: cones

Hi!

I am enjoying debugging aframe-physics-system with the debug option set to true so I can see the wireframes.

However, the cone wireframes seem inverted, even though the physics system is actually reading the real geometry, not the wireframe geometry. It's possible that just the wireframe is inverted by accident?

For reference:
screen shot 2017-07-31 at 2 15 12 pm

Constrained objects and collision

Hi,

I have two objects that I constrain to each other with a lock constraint, but they constantly collide and spin out of control once connected, even if collideConnected is set to false on both.

Am I using constrains incorrectly?

Is it possible to nest entities without physics?

I have this A-Frame scene graph:

<a-box id="cardboard" dynamic-body="mass: 0.01" position="0 0.9 -0.60" geometry="width: 0.05; depth: 0.05; height: 0.003" color="#008000">
      <a-box id="chip" position="0 0.002 0.01" geometry="width: 0.02; depth: 0.02; height: 0.001" color="#000"></a-box>
</a-box>

I want the nested box to not have physics and keep its position relative to its parent. But as soon as I came up with this setup, running the simulation make collision body to be misplaced. What am I doing wrong?

screenshot-eata - entrenador virtual-1496083743593

Attraction to origin forces

Do you have some clue how can i apply forces to reproduce this effect of bigger attraction when an object is far from origin position and slow down when arriving at origin?

https://youtu.be/RLEEVGxu_k8?t=3m16s

And if physics is the best approach to this (as it can collide things on the path) or may be handled with animation?

Thanks in advance

applyImpulse not working on dynamically generated entity?

I've been trying for a week now to piece together a physics-based projectile system. I pieced together a few examples from here on how to get applyImpulse to work on a dynamically generated entity.

Reduced test case: https://codepen.io/davatron5000/pen/XgQzEK/?editors=0010

  • Using the undocumented body-loaded event.
  • Copypasta of the working ForcePush example.
  • Objects have a body, hit the ground, and stack up because they have no foward momentum.
  • Don mentioned in Slack that this might need a setTimeout but when that's applied, objects hit the floor THEN have the impulse applied.

Not sure if there's a better way to do this or if something is broken here. Filing an issue per @donmccurdy recommendation in Slack.

.obj elements not recognized

Using the static-body component does not work on .obj files. The debug mode shows no wireframe around the object. It works perfectly on simple geometries though.

I am using the component like this:

<a-entity obj-model="obj: url(./img/mini-house.obj)" static-body="shape:box" mtl="color:blue; side:double"></a-entity>

Doesn't listen for all types of geometry loading?

While I was playing around with Kevin's text-geometry component I noticed that adding the physics component from HTML on the page or from the inspector on an entity that already had text-geometry, it loads physics, but doing it programmatically, like say:

var newText = document.createElement('a-entity')
newText.setAttribute('text-geometry', 'value', "foo")
newText.setAttribute('dynamic-body', 'shape', 'box')
this.el.sceneEl.appendChild(newText)

the physics never loads -- the best indication I have is that no debug wireframe appears and the elements don't seem to get pushed in the sim tree in the physics system. Per my @donmccurdy's discussion in the Slack, probably need to listen for different type of attaching geometry?

Glitch for example ("dog?" falls because it's initialized at page load, but the text generated when you click doesn't get simulated behavior event though it has a valid dynamic-body attribute)

Physics not active on new components

I'm surely doing something wrong here, but here is a super basic example of what I'm trying to do (real implementation is in aframe-react).

# html snippet
<a-scene id="myscene" physics="debug: true">

</a-scene>

From console in browser:

var box = document.createElement('a-box')
box.setAttribute('dynamic-body', '');
document.getElementById('myscene').appendChild(box)

The box is appended with the proper dynamic-body attribute, but it acts as though it is a normal entity with no physics attached.

Do I need to create a custom component in order for this to work properly?

Updating scale of physics bodies

Is there an efficient way to update the size of physics bodies to match changes to entity scale? It can be accomplished via removeBody and initBody, but this seems to have a cumulative impact on performance.

static-body components do not collide with each other

It's not clear from the documentation, but static-body components do not appear to collide with each other?

In this example you can use WASD to move the green box. The blue box never registers 'collide'. Is this by design? If so, is there a way to use the (very useful) collision system outside of dynamic-body?

<html>
<head>
	<script src="dist/aframe-v0.4.0.js"></script>
	<script src="dist/aframe-physics-system.js"></script>

	<script>
		AFRAME.registerComponent('detect-collision', {

		  init: function ( t ) {

			this.el.addEventListener( 'collide', function ( e ) {
				console.log( 'collision' );
			} );
		  }
		} );
	</script>
</head>
<body>
	<a-scene physics="debug: true">

		<a-entity camera></a-entity>
		<a-box static-body color="green" position="-2 0 -3" wasd-controls reset-on-collision></a-box>
		<a-box static-body color="blue" position="0 0 -3" detect-collision></a-box>

	</a-scene>
</body>
</html>

Add some utility components

  • force="1 0 0"
  • proximity-force="maxDistance: 2;" (allow things to hover, or push away from others?)
  • rotation-constraint="y" (limit rotation to y axis)
  • position-constraint="x, z" (limit movement to x and z axes)

_wakeUpAfterNarrowphase' of undefined

Hi ! I was playing and creating a simple shot game, when click I add via createElement a a-sphere child and applyImpulse when collision is detected I remove the bullet and the target (the other object) and have that error
Uncaught TypeError: Cannot read property '_wakeUpAfterNarrowphase' of undefined at World.internalStep (aframe-physics.min.js:7) at World.step (aframe-physics.min.js:7) at r.tick (aframe-physics.min.js:8) at aframe.min.js:250 at Array.forEach (<anonymous>) at HTMLElement.value (aframe.min.js:250) at HTMLElement.value (aframe.min.js:250) at aframe.min.js:369

Am I doing something wrong? and other thing is that if add dynamic-body to a entity created via javascript
(like createElement) the body propery doesnt exists so I use a 1s timeout hack to use the body property

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.