pmndrs / cannon-es Goto Github PK
View Code? Open in Web Editor NEWThis project forked from schteppe/cannon.js
💣 A lightweight 3D physics engine written in JavaScript.
Home Page: https://pmndrs.github.io/cannon-es/
License: MIT License
This project forked from schteppe/cannon.js
💣 A lightweight 3D physics engine written in JavaScript.
Home Page: https://pmndrs.github.io/cannon-es/
License: MIT License
After adding a convex collision body to the imported model, the test found that the collision between box and convex did not work properly
Demo is here
You can change the shape of the red object used for the test.
In Getting started in Cannon-es docs
Code is
const groundBody = new CANNON.Body({
type: Body.STATIC,
shape: new CANNON.Plane(),
})
groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // make it face up
world.addBody(groundBody)
It throws Uncaught ReferenceError: Body is not defined
Whereas it should be:
const groundBody = new CANNON.Body({
type: CANNON.Body.STATIC,
shape: new CANNON.Plane()
})
groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0)
world.addBody(groundBody)
Cause we aren't importing Body directly into our script.
Same mistake here:
cannon-es/src/solver/SplitSolver.ts
Line 22 in f185940
I believe the subsolver should have the type Solver or something else, and not SplitSolver otherwise it doesn't seem to be possible to construct this object.
To reproduce, change all heightfield data points in the heightfield.html
demo to -5. You will see 1,000+ errors thrown from ConvexPolyhedron
when computing convex triangle pillars.
This was also an issue from 2014: schteppe#149
Once passing a Geometry with verticies and faces to ConvexPolyhedron, the arrays of both get stripped, this breaks the ability to use the ConvexPolyhedron. Another issue is that ConvexGeometry strips the bounding shapes (both box and sphere), not sure if this is causing the error
TypeError: Cannot read property 'vsub' of undefined at Function.ConvexPolyhedron.computeNormal
An example is here
https://codesandbox.io/s/convexpolyhedron-test-pjwrr?runonclick=1&file=/src/index.js
To see the issue, toggle the bool on line 58
Given the recent switch to the pmndrs organization, the URL for this repo should be updated to https://pmndrs.github.io/cannon-es/ as the current one yields a 404.
I got a sphere body with a changing quaternion, I just want that body to move forward according to its quaternion. I found many topics related to that but none of the suggested codes is working.
Is it a simple way to achieve that simple task?
I guess the problem happened after #54 and after upgrading dependencies. Basically these lines throw the following typescript error.
TypeError: Converting circular structure to JSON
I commented them temporarly.
cannon-es/src/world/World.test.ts
Lines 90 to 93 in d9cb52d
yarn test
Editors like VS Code parse the comments from source code and display them during editing.
Through this I realized that the constructors of classes like "World" and "Body" are falsely shown as deprecated because the comments above their constructors seem to be weirdly positioned or not correctly formatted. One example:
dist/cannon-es.js
line 3154
/**
* Base class for all body types.
* @example
* const body = new Body({
* mass: 1,
* })
* const shape = new Sphere(1)
* body.addShape(shape)
* world.addBody(body)
*/
class Body extends EventTarget {
line 3224
/**
* Callback function that is used BEFORE stepping the system. Use it to apply forces, for example. Inside the function, "this" will refer to this Body object. Deprecated - use World events instead.
* @deprecated Use World events instead
*/
/**
* Callback function that is used AFTER stepping the system. Inside the function, "this" will refer to this Body object. Deprecated - use World events instead.
* @deprecated Use World events instead
*/
line 3379
/**
* When true the body behaves like a trigger. It does not collide
* with other bodies but collision events are still triggered.
* @default false
*/
constructor(options = {}) {
The comments from line 3224 seem to be misinterpreted and falsely mark the constructor signatures as deprecated.
Steps to reproduce:
dist/cannon-es.js
into another scriptIf these comments are removed, the constructor is no longer seen as deprecated. As such, I suggest reformatting such comments to make it clear that they are not referring to the constructor signature but to the respective fields.
Hey all!
Arriving from schteppe#438 and very happy to see a fork actively maintanted.
The README here still says "Visit the original project for full documentation and examples." but the reality is the original project is "[...] slowly disintegrating. Piece by piece." :-D
I see everything is typescripted now, so there must be some good tools out there now, better than YUI for sure!
How can we help get this documentation website up?
Hi,
Thanks for great library and great team.
I'm learning about ThreeJs and Cannon-es. In my example I'm working with Cylinder but I see Cylinder is not working well. I create a cylinder and sphere then when I click by mouse I make sphere run then sphere goes through Cylinder. It shouldn't.
This is full my example.
example.zip
Thanks
More of a note than an issue, but using pika instead of / in addition to rollup would allow future-proofing the consumption of the package in several preferred formats, with ESM as the default dist
:
https://www.pika.dev/blog/introducing-pika-pack/
Don't want to overpromise, but I can take a look later 👍
Hey,
First of all, this is a duplicate issue from another repository (three-to-cannon) that seems like to be not related to it at all.
I used three-to-cannon first, then I switch for another method manually, both gave me the same results.
Uncaught TypeError: Cannot read property 'x' of undefined at Vec3.copy (cannon-es.js:915) at ConvexPolyhedron.clipFaceAgainstHull (cannon-es.js:2593) at ConvexPolyhedron.clipAgainstHull (cannon-es.js:2335) at Narrowphase.convexConvex (cannon-es.js:11067) at Narrowphase.getContacts (cannon-es.js:10759) at World.internalStep (cannon-es.js:12774) at World.step (cannon-es.js:12650) at animate (index.js:149)
I've been getting this error when two bodies with the hull settings collide with each other. My knowledge about geometries is pretty low, so I don't really understand what is happening. I found this (schteppe#459) in the CannonJS issues tab, might be useful.
Edit: I forgot to say that I merged the vertices as user "Dannie226" said, and it didn't change the problem, so I'm assuming that the fact that I'm using cannon-es is the whole reason it didn't solved it.
Any help would be greatly appreciated!
Hi,
would be nice to get this Box Shape collide with a Trimesh
Demo fails in browser (Brave) - console log below
Navigated to https://pmndrs.github.io/cannon-es/examples/threejs_fps
threejs_fps:50 GET https://pmndrs.github.io/cannon-es/examples/js/PointerLockControlscannon.js net::ERR_ABORTED 404
I'm trying to recreate the multiball object (but in 3D) as shown in this video. when you press your finger on a certain point the ball follow the specific direction.
Only problem is I don't know how to perform that with cannon js. I've tried setting a gravity of 0 with a velocity without any success. I'm wondering if I shouldn't update only three js and get rid of cannon js on this part. Many thanks in advance (tell me if you prefer me using stackoverflow, I would'nt like to overflow your issue area). Thanks
ps: you can download the app on this page press "e" to play around with the object
Hi all!
I started to develop a small game with CannonJS. The game has to work on the server side (NodeJS) and Cannon is light enough for that purpose. The physics engine should run at 30FPS.
I noticed that CannonJS had not been maintained for a few years, so i decided today to migrate to Cannon-es because the project is more alive. I had to adapt my code to use the ES6 module with NodeJS. However, i have the same problems i had with CannonJS.
My decor is made with boxes and ramps (a custom shape). My charactere is made with a set of a wheel,a cylinder and a HingeConstraint.
My problem is that my character remains blocked/stuck in my decor especially during a jump. I will tend to think that this is due to a bad setting for 30FPS but i don't enough know the physic engine to know which parameters to adapt (there are so many!). I took the parameters that i found as an example for CannonJS (i tried to change some parameters but without success). Maybe it's due to a limitation of the physic engine?
var world = new CANNON.World();
world.quatNormalizeSkip = 0;
world.quatNormalizeFast = false;
world.defaultContactMaterial.contactEquationStiffness = 1e9;
world.defaultContactMaterial.contactEquationRelaxation = 4;
var solver = new CANNON.GSSolver();
solver.iterations = 7;
solver.tolerance =0.1;
world.solver = new CANNON.SplitSolver(solver);
world.gravity.set(0,-40,0);
world.broadphase = new CANNON.NaiveBroadphase();
world.broadphase.useBoundingBoxes = true;
var fixedTimeStep = 1.0 / 30.0; // seconds
var maxSubSteps = 3;
What would be the right settings to run at 30FPS?
I created a small online demonstration to show the problem: https://littleworldofsatoshi.com/testRamp
I'm trying to add a PR to use-cannon
to be able to scale multiple types of bodies, I've managed to make it work for box and sphere with
const shape = state.bodies[uuid].shapes[0]
if (type === 'Box') {
shape.halfExtents.set((args[0] * scale[0]) / 2, (args[1] * scale[1]) / 2, (args[2] * scale[2]) / 2)
shape.updateConvexPolyhedronRepresentation()
} else if (type === 'Sphere') {
shape.radius = args[0] * scale[0]
state.bodies[uuid].updateBoundingRadius()
}
But when I try to scale a Cylinder
it doesn't work, I've tried everything I know 😅
const shape = state.bodies[uuid].shapes[0]
else if (type === 'Cylinder') {
const body = state.bodies[uuid]
state.world.removeBody(body)
body.removeShape(shape)
shape.radiusTop = args[0] * scale[0]
shape.radiusBottom = args[1] * scale[1]
shape.height = args[2] * scale[2]
shape.numSegments = args[3] * scale[3]
shape.updateBoundingSphereRadius()
shape.computeEdges()
shape.computeNormals()
body.addShape(shape)
body.updateBoundingRadius()
body.updateAABB()
body.updateMassProperties()
body.updateSolveMassProperties()
body.updateInertiaWorld()
body.wakeUp()
state.world.addBody(body)
syncBodies()
}
But with no prevail 😅
I'm mostly trying by trial and error because I didn't find stuff like this in the docs
Hope someone can help me out, I've been wanting to do this PR because I was trying to add Cheat Codes to pmndrs/racing-game
and one of the cheat codes is to scale the car 😄
We tried to get collisions between different convex polyhedrons based on simplified models loaded as GLB.
The collisions are very unreliable but happen sometimes, most of the time objects just fall through each other.
Against planes and boxes the models behave as expected but not on each other.
I am not sure if the problem is with the models or the implementation.
Is there some documentation about requirements to make such things possible?
Demo (red objects are fixed):
https://eww7v.csb.app/
I'm looking into updating a couple packages' dependencies from a custom fork of cannon.js
to cannon-es
. When installing and running my tests, however, I'm seeing the error about @babel/runtime
below. Looking at the generated output on unpkg, I see the dependency on @babel/runtime
as well. I'm not particularly familiar with using Babel directly, and it's not part of my package. Is that supposed to be a runtime dependency? I'm assuming not, but if so shouldn't it be declared in dependencies
or peerDependencies
?
The project I'm updating now is three-to-cannon, and the issue can be reproduced with npm install && npm run dist && npm test
after cloning the repo. Note that it's a library, not an application: I declare cannon-es
as a peer dependency rather than bundling it with the package, and I cannot transpile cannon-es
on behalf of my users.
> three-to-cannon@2.0.0 test /Users/donmccurdy/Documents/Projects/three-to-cannon
> node test/index.js
internal/modules/cjs/loader.js:775
throw err;
^
Error: Cannot find module '@babel/runtime/helpers/possibleConstructorReturn'
Require stack:
- /Users/donmccurdy/Documents/Projects/three-to-cannon/node_modules/cannon-es/dist/index.cjs.js
- /Users/donmccurdy/Documents/Projects/three-to-cannon/dist/three-pathfinding.js
- /Users/donmccurdy/Documents/Projects/three-to-cannon/test/index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:772:15)
at Function.Module._load (internal/modules/cjs/loader.js:677:27)
at Module.require (internal/modules/cjs/loader.js:830:19)
at require (internal/modules/cjs/helpers.js:68:18)
at Object.<anonymous> (/Users/donmccurdy/Documents/Projects/three-to-cannon/node_modules/cannon-es/dist/index.cjs.js:7:1)
at Module._compile (internal/modules/cjs/loader.js:936:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
at Module.load (internal/modules/cjs/loader.js:790:32)
at Function.Module._load (internal/modules/cjs/loader.js:703:12)
at Module.require (internal/modules/cjs/loader.js:830:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/Users/donmccurdy/Documents/Projects/three-to-cannon/node_modules/cannon-es/dist/index.cjs.js',
'/Users/donmccurdy/Documents/Projects/three-to-cannon/dist/three-pathfinding.js',
'/Users/donmccurdy/Documents/Projects/three-to-cannon/test/index.js'
]
}
npm ERR! Test failed. See above for more details.
We are considering using cannon-es
in three.js but seems like there's a performance regression.
@Mugen87 converted cannon.js to modules and here's the running example:
https://raw.githack.com/mrdoob/three.js/dev/examples/physics_cannon_instancing.html
This is the same example using cannon-es
:
https://raw.githack.com/Mugen87/three.js/dev45/examples/physics_cannon_instancing.html
after i upgraded my cannon-es to 0.11.0 i face this error:
ERROR in ./node_modules/cannon-es/dist/cannon-es.js
Module not found: Error: Can't resolve 'perf_hooks' in '/mnt/c/Projects/game/node_modules/cannon-es/dist' @ ./node_modules/cannon-es/dist/cannon-es.js 12202:16-37
@ ./src/server/game/game/Scene.ts
@ ./src/server/game/game/Renderer.ts
@ ./src/server/game/game/index.ts
@ ./src/view/app.ts
@ ./src/view/index.ts
here is my webpack config file
`
/* eslint-disable */
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { ProvidePlugin, HotModuleReplacementPlugin } = require("webpack");
require("dotenv").config({ path: __dirname + "/.env" });
module.exports = (env) => {
return {
mode: "development",
entry: "./src/view/index.ts",
devtool: "inline-source-map",
devServer: {
contentBase: "./dist/view",
port: process.env.WEBPACK_PORT,
open: false,
hot: true,
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: "public/index.html",
inject: "body",
minify: {
html5: true,
removeComments: true,
collapseWhitespace: true,
},
templateParameters: {
PUBLIC_URL: "",
},
}),
new CopyWebpackPlugin([
{
from: "public",
ignore: ["index.html"],
},
]),
new ProvidePlugin({
jQuery: "jquery",
$: "jquery",
_: "lodash",
}),
new HotModuleReplacementPlugin({}),
],
output: {
filename: "static/js/[name].[hash].js",
chunkFilename: "static/js/[name].[hash].chunk.js",
path: path.resolve(__dirname, "dist/view"),
publicPath: "/",
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
optimization: {
usedExports: true,
moduleIds: "hashed",
runtimeChunk: "single",
splitChunks: {
cacheGroups: {
vendor: {
test: /[\/]node_modules[\/]/,
name: "vendors",
chunks: "all",
},
},
},
},
module: {
rules: [
{
test: /.tsx?$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: ["@babel/preset-env", "@babel/preset-typescript"],
plugins: ["@babel/plugin-proposal-class-properties"],
},
},
{
test: /.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /.(png|svg|jpe?g|gif)$/i,
loader: "file-loader",
options: {
name: "[ext]/[name].[hash].[ext]",
outputPath: "assets/images",
},
},
{
test: /.(woff|woff2|eot|ttf|otf)$/,
loader: "file-loader",
options: {
name: "[ext]/[name].[hash].[ext]",
outputPath: "assets/fonts",
},
},
{
test: /.(gltf|glb|bin)$/,
use: [
{
loader: "file-loader",
options: {
name: "[ext]/[name].[hash].[ext]",
outputPath: "assets/3DModles",
},
},
],
},
],
},
};
};
`
Hi, and thanks for great libs !
Bodies falls asleep ( when <Physics allowSleep={true}>
), but after, wont move with applyImpulse/Force without wakeUp.
World.time
is reporting a number twice that what it should.
I wrote a simple test case:
const world = new World()
for(let i = 0; i < 60; i++) {
world.step(1/60)
}
expect(world.time).toBeCloseTo(1)
which fails with the message:
Expected: 1
Received: 1.9999999999999978
I looked at the world code and for a fixed time step the internal time counter is incremented twice, once here in the actual World.step function:
Line 395 in cebdad1
Line 761 in cebdad1
I'm not sure which one is the redundant one
meshoptimizer use interleavedBuffer for the glb optimation
this needs to be conferted to BufferAtrributes as input for the Trimesh Shape
https://codesandbox.io/s/trimesh-test-meshopt-2l4wt?file=/src/index.js
( load the unoptimized glb works fine loadModel("../public/diamond.glb");)
As discussed on Discord, this is a suggestion to add an applyTorque
function to Body
that lets the user apply a rotational force.
Body.torque
represents the current rotational force of the body that will be applied in the next physics step and then reset (if I understand things correctly.) The proper way to explicitly apply a rotational force to a body is to set, or modify, this vector. It works, but it's something that isn't clearly documented, or easy to find.
A possible implementation of Body.applyTorque
would accept a Vec3 and vadd it to the existing torque, similar to how Bullet does it (link courtesy of Marco), or the part of the existing applyForce that applies the rotational force resulting from an offset force.
I know this isn't the place to ask this, I'm very new to physics and games in general.
How do I rotate a cannon body at a constant speed when holding down the "a" or "d" key.
I'm trying to implement a controller for a fbx model and I'm having some issues regarding rotations and jumping.
Currently for forward and jump I do something like:
If(jump){
Body.position.y+=5
}
if(forward){
Body.position.z+=5
}
Is this method fine or should I use velocity? The jump statement has been giving me some issue as well.
I have a very simple TypeScript example in cannon that just print a gravity:
import "cannon";
function main()
{
const physicsWorld = new CANNON.World();
physicsWorld.gravity.set(0, -9.82, 0);
console.log("gravity = ", physicsWorld.gravity);
}
main();
You can run it on playground: https://plnkr.co/edit/EoxKFFYZgtXnTTEX?preview
Source code on GitHub with cannon: https://github.com/8Observer8/hello-cannon-ts
Source code on GitHub with cannon-es: https://github.com/8Observer8/hello-cannon-es-ts
When I try to change "cannon" to "cannon-es", for example, this line:
import "cannon"
on this line:
import * as CANNON from "cannon-es";
I get this error: Uncaught ReferenceError: exports is not defined
and this error: Uncaught TypeError: Cannot read property 'World' of undefined
I have group of object, also all objects added to this group gets centered and the position (0,0,0) inherits from the group world position. My problem is that it's heavy and error prone.
I always need to subtract the position by half the size of my object. Is there a particular method to use in that case? If you can't get an answer I'll try making an example.
Thanks in advance,
(by the way I'm a newbie in the world of 3D and physics)
new CANNON.Ray(vFrom, vTo).intersectBody(body)
method doesn't work without using ray.updateDirection
method (which was private in cannon.js).
body.addEventListener("collide", ({ contact }) => {
if (!grounded) {
const vFrom = body.position;
const vTo = new CANNON.Vec3(0, -1, 0);
const ray = new CANNON.Ray(vFrom, vTo);
ray.updateDirection(); // <------ I shouldnt need to update the direction
// manually before using intersectBody
ray.intersectBody(contact.bi);
grounded = ray.result.hasHit;
}
});
A bug also encountered here but you should dig into the code.
Also, thanks for your port and fork !
Hey,
would it be possible to allow Shape sleep? the idea is to have one body with multiple Trimesh Shapes
and lets the Shape sleep if the Character is not near. ( near distance could be done with bvh https://github.com/gkjohnson/three-mesh-bvh)
Hello,
Thanks for maintaining cannon!
I have an error when I create ConvexPolyhedron, I must miss something
I have a few errors when creating a ConvexPolyhedron Body :
cannon-es.js:2247 .faceNormals[0] = Vec3(0,0,-0.9999999999999999) looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right-hand rule.
My process :
Code :
CreateConvexPolyhedron(geometry, scaleVec) {
if (!geometry.vertices) {
geometry = new THREE.Geometry()
.fromBufferGeometry(geometry)
.scale(scaleVec.x, scaleVec.y, scaleVec.z)
geometry.mergeVertices()
geometry.computeBoundingSphere()
geometry.computeFaceNormals()
}
const points = [],
faces = []
points = geometry.vertices.map(function (v) {
return new CANNON.Vec3(v.x, v.y, v.z)
})
faces = geometry.faces.map(function (f) {
return [f.a, f.b, f.c]
})
return new CANNON.ConvexPolyhedron({ vertices: points, faces })
}
Help would be more than welcome :)
Thanks
Hello guys. I have a minor issue in my game development with materials bouncing of each other, which I would like to clamp to a specific speed during the endContact event which occurs on the world. This event emits two bodies, which are explicitly changed into null inside the framework:
beginContactEvent.bodyA = beginContactEvent.bodyB = null;
as well as
endContactEvent.bodyA = endContactEvent.bodyB = null;
This creates multiple issues in the event handling process. Would you be able to repair it or just return the actual bodies?
Thank you for the response.
Hello, glad to see some active development on this.... This is the update I did from cannon.js, updated to here (work in progress)
https://github.com/d3x0r/cannon.js/tree/d3x0r-lnQuat
Mostly just https://github.com/d3x0r/cannon.js/blob/d3x0r-lnQuat/src/math/lnQuaternion.ts Although Mat3 and Transform have Quaternion intimate knowledge. I added a method setQuat
to both quaternion and lnQuaternion classes, which is like a 'copyInto'... for the final conversion between the physics and three.js - requires updating some of the demo code...
need to copy src/math/ln*.ts
to src/math/*.ts
imports are hard to replace than requires were
https://d3x0r.github.io/cannon.js/
I think it would be helpful for people who are testing different collision body types to include the debug renderer. Great port btw!
Official example
Hey,
would it be possible to integrate CCD work from schteppe#366
the source should be https://github.com/bllem/cannon.js/commits/master
I have a simple cannon.js (cannon-es) scene three.js scene set up where 2 boxes are present, and 1 of the boxes moves forwards and backwards on command of the W and S keyboard keys.
But currently i have an issue such that when the 2 boxes collide, they sorta overlap each other before the physics takes effect onto box bodies, even at slow speed.
I've tried adjusting the mass, friction and restitution of the bodies. also tried different broadphases to no avail.
What could be the issue here? Strangely there's no overlap issue between the floor and the box bodies.
If included a gif capture of this issue here:
https://i.stack.imgur.com/eFEzG.gif
/*** Physics ***/
const world = new CANNON.World();
world.broadphase = new CANNON.SAPBroadphase(world);
world.allowSleep = true;
world.gravity.set(0, -9.82, 0);
// Default material
const defaultMaterial = new CANNON.Material('default');
const defaultContactMaterial = new CANNON.ContactMaterial(defaultMaterial, defaultMaterial, {
friction: 0.1,
restitution: 0.1,
});
world.defaultContactMaterial = defaultContactMaterial;
// Floor
const floorShape = new CANNON.Plane();
const floorBody = new CANNON.Body();
floorBody.mass = 0;
floorBody.addShape(floorShape);
floorBody.quaternion.setFromAxisAngle(new CANNON.Vec3(-1, 0, 0), Math.PI * 0.5);
world.addBody(floorBody);
/*** Utils ***/
const objectsToUpdate = [];
// Create box
const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
const boxMaterial = new THREE.MeshStandardMaterial({
metalness: 0.3,
roughness: 0.4,
// envMap: environmentMapTexture,
});
var boxes_mesh = [];
const createBox = (width, height, depth, position) => {
// Three.js mesh
const mesh = new THREE.Mesh(boxGeometry, boxMaterial);
mesh.scale.set(width, height, depth);
mesh.castShadow = true;
mesh.position.copy(position);
scene.add(mesh);
// Cannon.js body
const shape = new CANNON.Box(new CANNON.Vec3(width * 0.5, height * 0.5, depth * 0.5));
const body = new CANNON.Body({
mass: 0.1,
position: new CANNON.Vec3(0, 3, 0),
shape: shape,
material: defaultMaterial,
});
body.position.copy(position);
// body.addEventListener('collide', playHitSound);
world.addBody(body);
boxes_mesh.push(body);
// Save in objects
objectsToUpdate.push({ mesh, body });
};
/// create 2 boxes at the start
createBox(1, 1.5, 2, { x: 0, y: 3, z: 0 });
createBox(0.5, 0.5, 0.5, { x: -3, y: 3, z: 0 });
/*** Floor ***/
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(10, 10),
new THREE.MeshStandardMaterial({
color: '#777777',
metalness: 0.3,
roughness: 0.4,
})
);
floor.receiveShadow = true;
floor.rotation.x = -Math.PI * 0.5;
scene.add(floor);
render loop
const tick = () => {
const elapsedTime = clock.getElapsedTime();
const deltaTime = elapsedTime - oldElapsedTime;
oldElapsedTime = elapsedTime;
// Update physics
world.step(1 / 60, deltaTime, 3);
// onkeydown "W" or "S"
if (moveForward == true) {
boxes_mesh[1].position.x += 0.05;
}
if (moveBackward == true) {
boxes_mesh[1].position.x -= 0.05;
}
for (const object of objectsToUpdate) {
object.mesh.position.copy(object.body.position);
object.mesh.quaternion.copy(object.body.quaternion);
}
// Update controls
controls.update();
// Render
renderer.render(scene, camera);
// Call tick again on the next frame
window.requestAnimationFrame(tick);
};
Hi, I'm trying to add a physics object onto a loaded fbx model. I managed to add a cannon cylinder around my model by using the dimensions of of bounding box around my model.
I'm having issues trying to keep the cylinder around during animations.
I can move the cylinder using:
CharacterBody.position.z += 5
//Sync model and mesh
Character.position.copy(CharacterBody.position)
Character.quaternion.copy(CharacterBody.quaternion)
But during a walk animation for example the model moves much quicker than the box itself.
I know that the body has a velocity but I'm nor sure how to use it.
I've tried:
CharacterBody.velocity.z =5
but nothing happens.
I use Cannon with Babylon.js
https://doc.babylonjs.com/divingDeeper/physics/usingPhysicsEngine
I see many examples with Three.js, but not with Babylon.js, or other frameworks
Is this package for Three.js only?
This issue is readily apparent when using a wireframe debugger for the physics bodies.
We may want to allow specifying the axis orientation in the cylinder constructor - since the most popular way to construct capsule physics bodies is with cylinder+sphere compound bodies, and the most popular capsule geometry primitives are aligned with the Cannon cylinder's current orientation (i.e. not aligned with Three's cylinder)
(cool (or uncool?) coincidence that it's issue 58 in both repos...)
When passing a timeSinceLastCalled
value to the world.step
method, the simulation performance quickly degrades beyond usability.
Spectrum chat: World step does not adapt to framerate
Per Schteppe (schteppe#371):
Perhaps the number of substeps are maxed out? This could happen if you, for example, pass in deltaTime in milliseconds instead of seconds... or if you accidentally calculate the value wrong for the first frame (there is no “previous” time value). or if the first deltaTime values are too large (they usually are larger during the first frames while the JIT is warming up).
What happens if you pass in 1000 substeps instead of 10? If you have implemented it correctly, changing the number of substeps should do nothing.
Hi! I noticed that cannon.js has a large suite of unit tests that seem to have not been ported over to this fork yet. Wondering if you'd be interested in having help doing that? Or if you're aware of any efforts to do that that are already in progress? It'd be a great way for me to understand Cannon (and physics rigs in general) as I work on a personal project using Cannon.
Heyhey,
first of all, thank you for maintaining this!
I'm using "vanilla" cannon.js in my SparkAR-projects (instagrams AR facefilter technology) and am writing a little wrapper for it. I install it using yarn into the project's script-directory, and from there I can work with it using TypeScript in WebStorm. As I understand it, SparkAR hot reloads the script files referenced in the project, after using webpack to bundle them to some temporary folder in the user directory - this is a bit of a black box.
To reduce bundle size in the face filter projects (and to work with a maintained library) I tried to switch from cannon to cannon-es. I also installed with yarn and can use the library completely normally with code-completion and type recognition. However, when importing cannon-es (or parts of it) into a new or ongoing project TypeScript-file and hot reloading, SparkAR throws this:
JavaScript error: Compiling JS failed: 14984:28:invalid expression Buffer size 1186988 starts with: 2866756e6374696f6e205f5f61726678
This is something happening internally of SparkAR to the bundled version of the script obviously, as it happens on line 14984, and I realize that it's not a problem of cannon-es per se. However, I have no idea how to debug this and haven't seen it with other libraries or modules. So I just wanted to ask if any of the contributers here have an idea what could be causing the invalid expression Buffer size
. For the moment I still had to switch back to cannon.js, which is working fine.
If needed information is missing from my post, please let me know, and sorry if it isn't apropriate to ask this here.
see: schteppe#122
and: schteppe#270
currently this is super unintuitive and it cannot be handled generically. use-cannon would have a hard time re-creating bodies just like that. would it be hard to give cannon bodies a simple scale: [x,y,z] prop?
Hi,
I loaded gltf scene then initialized my scene. for adding physics i converted Object3d into cannon with threeToCannon, after doing this my pins will fall and pass from the ground like the image bellow
i checked the position and they are correct.
every thing that isn't a trimesh stays on the ground, but trimesh elements pass th ground and go to the underground
It was a long time ago, so I don't remember much about it, but when I updated Cannon.js from v0.4.3
to v0.6.2
, there was a performance down. schteppe#310
I tried the library with cannon-es and the performance seems to be similar.
three.js + cannon.js v0.4.3 result:
https://cx20.github.io/jsdo.it-archives/cx20/qM1k/
three.js + cannon.js v0.6.2 result:
https://cx20.github.io/jsdo.it-archives/cx20/CeNf/
I'm not sure who told me about it, but it seems to be improved by applying the following monkey patch.
//////////////////////////////////////////////
//./cannon.js-0.6.2/src/math/Vec3.js + modified
//////////////////////////////////////////////
/**
* @method tangents
* @memberof CANNON.Vec3
* @brief Compute two artificial tangents to the vector
* @param CANNON.Vec3 t1 Vector object to save the first tangent in
* @param CANNON.Vec3 t2 Vector object to save the second tangent in
*/
var Vec3_tangents_n = new CANNON.Vec3();
var Vec3_tangents_randVec = new CANNON.Vec3();
CANNON.Vec3.prototype.tangents = function(t1, t2) {
const norm = this.length();
if (norm > 0) {
const n = Vec3_tangents_n;
const inorm = 1 / norm;
n.set(this.x * inorm, this.y * inorm, this.z * inorm);
const randVec = Vec3_tangents_randVec;
if (Math.abs(n.x) < 0.9) {
randVec.set(1, 0, 0);
n.cross(randVec, t1);
} else {
//randVec.set(0, 1, 0);
randVec.set(0, 0, 0); // TODO: This is a monkey patch to improve performance. Changed from 1 to 0
n.cross(randVec, t1);
}
n.cross(t1, t2);
} else {
t1.set(1, 0, 0);
t2.set(0, 1, 0);
}
}
The following is the result of applying the monkey patch.
three.js + cannon-es v0.17.1 + monkey patch result:
https://cx20.github.io/webgl-physics-examples/examples/threejs/cannon-es/domino/
I won't create a PR because I can't be certain that this fix is correct, but I hope it will help improve performance.
I’ve made a simple demo where a sphere is moving forward with a fixed velocity along a plane. Occasionally the position of the sphere will skip forward slightly, then immediately move back on the next frame (to the “expected” position). The demo gets the difference between the previous and current body.position.z
and reports out the highest value, and when skipping happens, it seems to be an actual double of the expected difference. There does not seem to be any relevant change in frame delta values. The jumpiness can sometimes happen very frequently and quickly, or sometimes take some time to manifest.
I initially filed this on the use-cannon
repo, but when I dropped that and used cannon-es
directly I noticed the exact same problem so I though I’d file something here, and hopefully someone has any insight. Is this just a fluke that happens on my end, or can anyone else recreate this issue on their end? What could be the issue here?
Add Body.prototype.recalculateCenterOfMass
to cannon-es
. Useful for recalculating center of mass after updating body shapes. See pmndrs/use-cannon#29 (comment)
I experimented with cloth simulation demo on react native using expo-three (three.js) renderer. I had to reduce the number of world iterations to 1-3 so that the model could barely render. If I increase the number of segments in cloth to 50x50, the whole thing gets completely stuck.
I was wondering if anyone else had similar issue on React Native or Web.
I would like to make a sphere bounce inside a box.
For the moment the sphere acts like there were a collision and quickly bounces off the cube when I position it at the center of box. I'm using THREE.js by the way. Many thanks in advance.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.