moveWithCollision issue -- quirks

Recommended Posts


I am simply trying to arrange items in a box (kind of like a shopping bag) however I am unable to "detect" collision correctly. In the example I created, I have two simple cylinders in a box; but the cylinders collide till the half of their radius. Also once they collide with the container (box) ... also half; you can never drag them back


Could you please advice what I am doing wrong.




Share this post

Link to post
Share on other sites

Hiya dhiru!   Hey, Arte beat me to it!  :)  But my answer is much more complicated, so I win.  heh


(sorry for the color changes.  you can re-adjust them)

This PG required quite a bit of work.  Not because you were doing anything wrong... but just because it is a challenging project.

Let's tour. 

Line 99 - The size of the cylinder collision .ellipsoid needed to be expanded a bit.  By default, the .ellipsoid is a little narrow.

Line 2 - The great createEmptyBox() function... needed a complete re-code.  This is because our built-in, non-physics-engine collision system... doesn't work on the inside of boxes.  So, I needed to make a box... out of 5-6 planes.  AND... our collision system works best...on the FRONT-side of planes, so all the front-sides of the planes... are aimed inward.

Test:  Drag a green cylinder.  This will re-attach your camera to the canvas.  (I could not get the initial camera attach in line 144... to work.  Causes error, not sure why, yet.)  Anyway, once your camera re-attaches, you can pan-around the new box... look it over... notice that all the backface culling is false, so you can see-thru all sides.... when viewing from the outside.

Oddness:  Every plane is set .isPickable = false (like line 14, 26, 38, etc).  Yet every plane is pickable and drag-able.  Not sure why THAT is happening, yet.

Lines 89/90... some mesh-merging lines... in case you want to make the 5-6 planes... into a single mesh again.

Lines 122/123 - I adjusted the two '55' values.  They are the Y-position of the cylinders.  They should move back to... oh... 52-53.  They are currently hovering above the box bottom, a bit.

Lines 219/220 area - we have seen in the past... that when using the getGroundPosition() function (from our playground drag'n'drop demo)... that sometimes it returns a Y value... that is < 0... and that can make mesh sink into the ground as you move them around.  These lines are testing/ensuring that the Y value returned from getGroundPosition()... stays at 0.  You may wish to do more tests in this area.

Ok, I guess we'll leave you to play.  Hope this helps.

We have done SOME testing on some issues... regarding collision .ellipsoids and .ellipsoidOffsets.  Here is one of our testing playgrounds.  https://www.babylonjs-playground.com/#WWCK0#80  WASDQE and shifted WASDQE keys active.  We have had some problems with colliding from top/bottom.  Q/E and shifted Q/E shows THIS demo... is doing OK with the vertical colliding.  Others have been "too soon", "too late"... and we occasionally get the "stuck-in-collision" problem that you described, too. 

This built-in collision system (non-physics-engine) is designed to be used for free cameras colliding with mesh (first-person shooters), and not for mesh colliding with other mesh.  But we have pushed its limits, a bit.  :)

I have created some special functions at the top of #80 playground... setEllipsoidPerBoundingBox() and showEllipsoid()... might be handy for your work, too.  Might be buggy.  :o

I believe... .ellipsoid is a vector3 -type value... and it is RADIUS values.  Half the width, height, and depth of the actual mesh.  But you might want to verify that.

Ok, I hope this helps.  As you can see with Arte's playground... things collide with outsides of boxes, but not so easy with insides.  Arte and I have played with collisions... for a few hours together, in the past.  It was fun.  :)  Now we have dhiru at the collisions party, too.  Should be a good time.

Share this post

Link to post
Share on other sites

Many thanks for this (this saves me so much time), I will start creating planes instead of a box.  

Just to give you an idea of how much you guys saved me  --- last night I wrote code to "correct" the overlap by recording the last correct value and changing it onPointerUp.  (talk about over engineering). But weirdly this only works if I move the cylinder slowly; and only correctly for the left cylinder (plus sometimes it does not work right) when I try to re-adjust. To further over-engineer--  I then decided to calculate the direction of the trajectory (slope of the line) and back out to the actual position such that they are just touching. (now you know how much you saved me).

Here is my foolish effort :)  http://playground.babylonjs.com/#32E8TZ

Need your suggestion : My final the goal is to be able to arrange objects so that I can "reliably" calculate the distances (given my the users arrangement) -- like a puzzle. -- my question is: do you think -- if the objects are arranged using this touch / collision feature -- the calculations be trustworthy (if I build a score)? -- I don't see why not; if all my objects are rigid bodies; please comment!!!


Thanks again,


Share this post

Link to post
Share on other sites

Good deal!   :)  Ahh, taking the long/wrong route... is all part of the learning fun.  I'm KNOWN for using 100 lines of code... to do 4 lines of work.  FAMOUS for it, even.  :D

But, you are surrounded by one of the finest learning environments ever... swell people, pretty nice docs, great playground, hoppin' forum.  You know.  This is a friggin' 24/7 3D experimenter's party.

Playground in-code search... it's great (once we know what keywords to search-for).  I really like this place, and this system.

Now, for some bad news.  Depending upon the shapes used for your puzzle pieces, you might not get the accuracy you want... from ellipsoid collisions system.  Too many "rounded edges".

If I were you, I would do some experiments with the BJS Action Manager... onIntersectionEnter/Exit.  Also, perhaps carefully examine our "intersection" playground... http://playground.babylonjs.com/?10  ... yet another way of monitoring for intersections.

When the shapes get more complex, that's when the intersection testing can become more sloppy and artifact-prone, in my opinion.  Let's look at the famous intersecting game... Operation.  Due to its unusual shapes and unusual-shaped holes in the board... a programmer MIGHT find that surrounding the "edge" with MANY little invisible intersection-testing "sensors"... is the way to go.  You might need to "poll" the sensors array in the renderLoop, constantly checking for intersectsMesh on all the edge-sensors, over and over.

AND, you should probably learn all you can... about "observers" and "observables".  There may be event-assistance features in that system.  Might be some good playground search terms.

In a way, you have two separate systems that need to cooperate.  The dragger, and the intersect testing.  Dragging is not always easy... in 3D.  Some programmers... choose to SELECT the mesh, and then use the mouse to press on-screen arrows... to move the mesh.

Arte and I once did "TriBarrels 59"... just a mess of attempting to drag stuff... with collisions... on all 3 axes.  Something to play-with, if you wish.  https://www.babylonjs-playground.com/#WWCK0#59

Sometimes you need to click "low" on the mesh... to get the cylinder dragging to work.  Sometimes it doesn't work at all.  Reload and try again... maybe hit some WASD keys first, or something.  Maybe try versions #58 or #60.  I'm still learning.  Not sure WHY it is reluctant to drag cylinders "first time".  hmm.  Adventures in dragging.  :)

Share this post

Link to post
Share on other sites

Hi Arte!  What does this fix?  Were the readouts screwed-up?  I wasn't paying much attention to them... but, nice find, thx! 

I still see failed cylinder dragging... when the scene first loads.  Click RUN again, all is better.  hmm.   Also a camera perspective change happens after re-RUN, too.

Really, the dragging of the wall cylinders WORKS FINE at initial load, just start click/drag about 4-5 cells below the cylinder.  Some sort of scaling/sizing issue... possibly involving those HTML readout lines.  Fun challenges.  :)  FF 52 ESR on Win 7

We also have a mouse wheel zoom-in problem... that camera.minZ = .001 doesn't solve.  Tri-grid disappears when I get too close.  :o  Sort-of like the girls I date.   ;)

Share this post

Link to post
Share on other sites

Back to studying observables -- I realize that I will have to use keyboards since it is difficult to move on the Z axis using mouse (vertical direction movement). 

I cannot thank you guys enough for saving so much of my time; If I had to build a game like "zenga"; and I wanted to calculate the force that comes on the most bottom tile, do the physics engines give me any kind of "force" output ? -- numerical values ? (just curious). -- also if/when I start using the Z axis in placing loads and apply gravity; it will fall to the bottom tile automatically and "balance" if there is space ? --right. 

Just curious how the keyboard will allow me to pick the object; how/when the gravity gets applied on objects.

Either ways, I now realize that I have a long way to go; many thanks;

I realize my doubts reveal that I don't have a lot of knowledge :) -- but I have to start somewhere.

Share this post

Link to post
Share on other sites

Hey dhiru, you're doing fine.  We all want to flatten the BJS learning curve as much as possible.  One of the best ways... is to get "borrowed" code into the hands of the new programmers... so they can learn "hands on" and "eyes on".  And you are kind and appreciative, and that makes it a pleasure for helpers, too.  Thanks for being that way! 

One of the things I/we have discovered... is that using a keyboard or mouse to move a physics-active mesh... can be troublesome.  The best way is to cooperate with the physics engine... instead of forcing it around.


WASD for camera... arrows keys to move the green p-mesh.  (p-mesh == physics-active mesh)  The red and blue boxes are also p-mesh, but not hooked to arrow keys.

See the little gray box?  That is ibox, a p-mesh that COULD be set invisible. 

Connecting the gray box to the green box... is an invisible physics "joint" (see line 80).  It is a "lock"-type of joint, which is essentially a fiberglass rod.  It has SOME flex, but not much.

Because of its "flex" and because it is a "device" of the physics engine system, it is "cooperative".  It acts as a bit of a flexible buffer...  between the gray ibox and the green 'player' box.

See the ibox "movers" in lines 108, 113, 118, 123?  Those "moves" happen INSTANTLY, and decisively.  POWERFUL instant ibox "shifts".  If we were to DIRECTLY apply those translate forces to the green box, the box would see a HUGE impact force... and go flying far far away.

But because of the "buffer joint" (the fiberglass rod) bolted between ibox and green box... things are softer... almost controllable.  SO, if a person REALLY needs to move-around a p-mesh with mouse or keypresses, a person SHOULD always install that (invisible) ibox and invisible joint.

Amount/Direction of linear (translational) or rotational force RECEIVED... is not an EASILY-measurable thing on the physics engines, as far as I know.   Keep reading, though.

Amount/Direction of forces that YOU APPLY, either with applyImpulse or applyForce/setForce... perfectly settable.  Also settable with velocities... how fast to thrust, or how fast to spin.

So, ya got some possible options... on the horizon.   One thing to keep in mind... is keypress auto-repeating when key is held.  This opens some possibilities to use mesh.physicsImpostor.applyImpulse(forceDirectionAndMagnitudeVector3, vector3PointOfContactUponMesh)... in little tiny amounts.  Pulse-thrusting.  The longer the user holds the key, the more pulsings... so the more velocity.  BUT, if the thrusted mesh was already pushing against a HUGE-MASS p-mesh with high ground friction (immovable)... then each thrust pulse WOULD NOT continue increasing the AMOUNT of force... because the force of each little impulse... is being instantly killed by the impact with the immovable.

Physics engines use invisible "bodies" called "impostors".  One is associated with each p-mesh.  They are often simple boundingBox/boundingSphere-like shapes. 

After a mesh becomes a p-mesh (a mesh with a physicsImpostor associated)... it uses Quaternion rotation... instead of Euler rotation.  Rotation values are no longer stored in mesh.rotation.  Instead, they are stored in mesh.rotationQuaternion.  (Just a little secret to remember, for later).  :)

I think you are the first forum person who has been interested in measuring "received force".  Most are just interested in applying force.  *shrug*. 

Also, we are nearing the limits of Wingnut's intelligence and experience levels, here.  Deep in the physics engines, which ARE written in JS so you CAN "go deep" if you wish, there IS received-force values found in the onCollide systems.  It is needed/used to calculate "restitution" (the amount of bounce/recoil from p-mesh impostor-impacts).

So, your experimenting future looks bright, dhiru.  I think you are home - good to have you aboard.  I look forward to seeing/feeling the explosions coming from your mad-scientist workshop.  :)

PS: https://www.babylonjs-playground.com/#15AFCG#31 has added physics engine speed,  via line 141.  vrrroooooom!

Share this post

Link to post
Share on other sites

Cannot thank you enough for so much explanation! -- I am going over it again to make sure I understand it.; I will definitely share with us once I have something to show.

When I saw your explanation and the playground link; my immediate impulse was to save the code along with the explanation before it got deleted :)

"The secret to creativity is knowing how to hide your sources".  Thanks again -- would have never got this far.

Share this post

Link to post
Share on other sites

Hi Wingnut/Arte, I build a simple scene where I allow adding cylinders one by one to arrange them as the user pleases (in a container) -- this works ok; but if I save the users work and reload the scene (from JSON)....every time I try to move the meshes they get removed from the scene!. There is no remove in my code; which means that I am missing to "set" something when I try to preload the scene. 

I tried to create it on the playground but since I don't have access to creating buttons that can simulate the "preloading" of assets --its hard. Would it be fine if I host it on a server and give you a link to see why the move causes the Meshes to get removed from the scene (its very strange). What is also weird is ..if I add the objects in the same scene one by one; only those meshes it allows to be moved (without getting removed).

Any advice would be helpful -- let me try to create an independent html that will simulate this so that I can attach it.



Share this post

Link to post
Share on other sites

Hi D.  I have questions.  :)

1.  Are you using physics engine?

2.  Are you selecting "which mesh to move" with mouse?

    2a.  If so, does selecting work ok?

3.  Is "move" done with keyboard or mouse-drag or...?

4.  If you are using mesh.ellipsoid and mesh.ellipsoidOffset (possibly with moveWithCollisions()) (non-physics engine)... are you saving each mesh .ellipsoid and .ellipsoidOffset in the json file?  Might you need to?

5. If you are using physics engine, does each mesh (after json load) have a mesh.physicsImpostor with proper mass, friction, and restitution settings as they did at JSON SAVE time?

[ console.log(mymesh.physicsImpostor) ]

That's some things you could check.  Use console.log LOTS LOTS LOTS.  Perhaps it did not REMOVE the mesh, but only moved it really far off-screen.  When a mesh disappears, try to do a console.log(scene.getMeshByName(itsName)) and see if it still exists.

If it does, next check its .position... see where it is located.  It could be far away, which means your mover is broken after JSON read-in/parse.

I will keep thinking.  Perhaps others will comment soon.  Console.log(anything) is your friend.  Put LOTS of them inside your code.  Learn to use your browser's object inspector... see if you can object-inspect the mesh after it has disappeared.

For example...  console.log(scene.getMeshByName(itsName)) might output to console... Object { state: "", metadata: null, doNotSerialize: false, _isDisposed: false, animations: Array[0],...}

In SOME browsers... you can click on the word 'Object' and another Dev Tools window will open... showing all the properties and methods on THAT object.  Scroll down down down... until you see .position.  Click that, and you can see the position... right there.  OR... you can do... console.log(scene.getMeshByName(itsName).position), too.  (if you don't like object inspectors)  :)

Anyway... that's the easiest way to find problem.  Console.log(everything)... see what goes wrong in a failed move.  Did mesh REALLY get removed, or just moved really far away... somehow?  Find those answers... and you might find your problem.  Good luck... report findings please.  thx.

Share this post

Link to post
Share on other sites

I am definitely not saving the mesh.ellisoid; but the strange thing is; when I add new objects they are able to recognize the loaded meshes (when using moveWithCollision()). It is only when I pick the old objects and try to move them when they vanish. 

Let me break my code and get all the scripts out in a neat HTML page so that I can show you the problem.

As always, many many thanks for your help.


Share this post

Link to post
Share on other sites

I simplified my code in order to highlight the issue (I was hoping it will automatically solve it -- but I am able to reproduce it even in my test code).  Also, I confirmed that I do create the ellipsoid, only because I call the exact same function. (when adding manually or via Json)


In the attached file (index.html); you will see "Edit work" on the top left corner ...if you selected "Create New" and keep adding cylinders while moving them after you add them one by one  ...you will find it is works fine ...it moves the cylinders ...allows me to add different sizes etc.  -- also it detects collisions correctly (also changing color as programmed).

However, if you selected "Create from Json" -- the data preloads the cylinders and as soon as you try to move them ...they disappear from the scene; 

The code to add cylinders by clicking on "Add Cylinder" -- (one by one) and ...adding cylinder from Json is 90% same; calls the same functions; yet the JSON loading does not work.

Please note : You will need to reload the page when switching between "Create from Json" and "Create New" .

Please let me know if you find anything obvious; while I am also trying from myside.



Share this post

Link to post
Share on other sites

Hi @dhiru 

When you loading from JSON, all positions you have as string. Before applying position to cylinder convert string to int.

Line: 285 in patterncreator.js

var myPositionVector = new BABYLON.Vector3(load.XPosition, load.YPosition, load.ZPosition);

change to

var myPositionVector = new BABYLON.Vector3(+load.XPosition, +load.YPosition, +load.ZPosition);


As @Wingnut mentioned "Use console.log LOTS LOTS LOTS", "Console.log(anything) is your friend".


Share this post

Link to post
Share on other sites

Many thanks for this; I feel sorry I could not find this on my own (not being lazy, just stupid), I actually tried to look at the logs could not spot it; please feel free to advise how you got it!.

Thanks again.

Share this post

Link to post
Share on other sites

Oh c'mon, Arte... give us all the details of how you found the problem.  Do you have a fancy error reporter that said "Hey, you're trying to set a vector3-type value with a string"  ??

Dousing/water-witching methods?  Ask questions to willow branches?

Consulted with Guru Tugginmypudha?

Can you "smell" bugs?  See them under special lighting?

Some kind of elixir that you drink?  Can you hear bugs talking?

C'mon, cough-up your secrets, Arte McParte.  :)

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.