OSDN Git Service

SDK:
[mikumikustudio/MikuMikuStudio.git] / sdk / jme3-documentation / src / com / jme3 / gde / docs / jme3 / advanced / physics.html
1
2 <h1><a>Physics: Gravity, Collisions, Forces</a></h1>
3 <div>
4
5 <p>
6
7 A physics simulation is used in games and applications where objects are exposed to physical forces: Think of games like pool billiard and car racing simulators. Massive objects are pulled by gravity, forces cause objects to gain momentum, friction slows them down, solid objects collide and bounce off one another, etc. Action and Adventure games also make use of physics to implement solid obstacles, falling, and jumping.
8 </p>
9
10 <p>
11 The jMonkeyEngine3 has built-in support for <object classid="java:org.netbeans.modules.javahelp.BrowserDisplayer"><param name="content" value="http://jbullet.advel.cz"><param name="text" value="<html><u>jBullet Physics</u></html>"><param name="textColor" value="blue"></object> (based on <object classid="java:org.netbeans.modules.javahelp.BrowserDisplayer"><param name="content" value="http://bulletphysics.org"><param name="text" value="<html><u>Bullet Physics</u></html>"><param name="textColor" value="blue"></object>) via the <code>com.jme3.bullet</code> package. This article focuses mostly on the RigidBodyControl, but also introduces you to others. 
12 </p>
13
14 <p>
15 If you are looking for info on how to respond to physics events such as collisions, read about <a href="/com/jme3/gde/docs/jme3/advanced/physics_listeners.html">Physics Listeners</a>.
16 </p>
17
18 </div>
19 <!-- EDIT1 SECTION "Physics: Gravity, Collisions, Forces" [1-867] -->
20 <h2><a>Technical Overview</a></h2>
21 <div>
22
23 <p>
24 jME3 has a complete, slightly adapted but fully wrapped Bullet <acronym title="Application Programming Interface">API</acronym> that uses normal jME math objects (Vector3f, Quaternion etc) as input/output data. All normal bullet objects like RigidBodies, Constraints (called &quot;Joints&quot; in jME3) and the various collision shapes are available, all mesh formats can be converted from jME to bullet.
25 </p>
26
27 <p>
28 The PhysicsSpace object is the central object in bullet and all objects have to be added to it so they are physics-enabled. You can create multiple physics spaces as well to have multiple independent physics simulations or to run simulations in the background that you step at a different pace. You can also create a Bullet PhysicsSpace in jME3 with a <code>com.jme3.bullet.BulletAppState</code> which runs a PhysicsSpace along the update loop, which is the easiest way to instantiate a physics space. It can be run in a mode where it runs in parallel to rendering, yet syncs to the update loop so you can apply physics changes safely during the update() calls of Controls and SimpleApplication.
29 </p>
30
31 <p>
32 The base bullet objects are also available as simple to use controls that can be attached to spatials to directly control these by physics forces and influences. The RigidBodyControl for example includes a simple constructor that automatically creates a hull collision shape or a mesh collision shape based on the given input mass and the mesh of the spatial it is attached to. This makes enabling physics on a Geometry as simple as &quot;spatial.addControl(new RigidBodyControl(1));&quot;
33 </p>
34
35 <p>
36 Due to some differences in how bullet and jME handle the scene and other objects relations there is some things to remember about the controls implementation:
37 </p>
38 <ul>
39 <li><div> The collision shape is not automatically updated when the spatial mesh changes</div>
40 <ul>
41 <li><div> You can update it by reattaching the control or by using the CollisionShapeFactory yourself.</div>
42 </li>
43 </ul>
44 </li>
45 <li><div> In bullet the scale parameter is on the collision shape (which equals the mesh in jME3) and not on the RigidBody so you cannot scale a collision shape without scaling any other RigidBody with reference of it</div>
46 <ul>
47 <li><div> Note that you should share collision shapes in general and that j3o files loaded from file do that as well when instantiated twice so this is something to consider.</div>
48 </li>
49 </ul>
50 </li>
51 <li><div> <strong>Physics objects remain in the physics space when their spatials are detached from the scene graph!</strong></div>
52 <ul>
53 <li><div> Use PhysicsSpace.remove(physicsObject) or simply physicsControl.setEnabled(false); to remove them from the PhysicsSpace</div>
54 </li>
55 </ul>
56 </li>
57 <li><div> If you apply forces to the physics object in an update() call they might not get applied because internally bullet still runs at 60fps while your app might run at 120.</div>
58 <ul>
59 <li><div> You can use the PhysicsTickListener interface and register with the physics space and use the preTick() method to be sure that you actually apply the force in the right moment.</div>
60 </li>
61 <li><div> Reading values from the physics objects in the update loop should always yield correct values but they might not change over several fames due to the same reason.</div>
62 </li>
63 </ul>
64 </li>
65 <li><div> Reading or writing from the physics objects during the render phase is not recommended as this is when the physics space is stepped and would cause data corruption. This is why the debug display does not work properly in a threaded BulletAppState</div>
66 </li>
67 <li><div> Bullet always uses world coordinates, there is no such concept as nodes so the object will be moved into a world location with no regard to its parent spatial.</div>
68 <ul>
69 <li><div> You can configure this behavior using the setApplyPhysicsLocal() method on physics controls but remember the physics space still runs in world coordinates so you can visually detach things that will actually still collide in the physics space.</div>
70 </li>
71 <li><div> To use the local applying to simulate e.g. the internal physics system of a train passing by, simply create another BulletAppState and add all models with physics controls in local mode to a node. When you move the node the physics will happen all the same but the objects will move along with the node.</div>
72 </li>
73 </ul>
74 </li>
75 </ul>
76
77 <p>
78
79 When you use this physics simulation, values correspond to the following units:
80 </p>
81 <ul>
82 <li><div> 1 length unit (1.0f) equals 1 meter, </div>
83 </li>
84 <li><div> 1 weight unit (1.0f) equals 1 kilogram,</div>
85 </li>
86 <li><div> most torque and rotation values are expressed in radians.</div>
87 </li>
88 </ul>
89
90 <p>
91
92 Bullet physics runs internally at 60fps by default. This rate is not dependent on the actual framerate and it does not lock the framerate at 60fps. Instead, when the actual fps is higher than the physics framerate the system will display interpolated positions for the physics objects. When the framerate is lower than the physics framerate, the physics space will be stepped multiple times per frame to make up for the missing calculations. 
93 </p>
94
95 <p>
96 Internally, the updating and syncing of the actual physics objects in the BulletAppState happens in the following way:
97 </p>
98 <ol>
99 <li><div> collision callbacks (<code>BulletAppState.update()</code>)</div>
100 </li>
101 <li><div> user update (<code>simpleUpdate</code> in main loop, <code>update()</code> in Controls and AppStates)</div>
102 </li>
103 <li><div> physics to scenegraph syncing and applying (<code>updateLogicalState()</code>)</div>
104 </li>
105 <li><div> stepping physics (before or in parallel to <code>Application.render()</code>)</div>
106 </li>
107 </ol>
108
109 </div>
110 <!-- EDIT2 SECTION "Technical Overview" [868-5940] -->
111 <h2><a>Sample Code</a></h2>
112 <div>
113
114 <p>
115
116 Full code samples are here:
117 </p>
118 <ul>
119 <li><div> <object classid="java:org.netbeans.modules.javahelp.BrowserDisplayer"><param name="content" value="http://code.google.com/p/jmonkeyengine/source/browse/trunk/engine/src/test/jme3test/bullet/TestBrickWall.java"><param name="text" value="<html><u>TestBrickWall.java</u></html>"><param name="textColor" value="blue"></object></div>
120 </li>
121 <li><div> <object classid="java:org.netbeans.modules.javahelp.BrowserDisplayer"><param name="content" value="http://code.google.com/p/jmonkeyengine/source/browse/trunk/engine/src/test/jme3test/bullet/TestQ3.java"><param name="text" value="<html><u>TestQ3.java</u></html>"><param name="textColor" value="blue"></object></div>
122 </li>
123 <li><div> <object classid="java:org.netbeans.modules.javahelp.BrowserDisplayer"><param name="content" value="http://code.google.com/p/jmonkeyengine/source/browse/trunk/engine/src/test/jme3test/bullet/TestSimplePhysics.java"><param name="text" value="<html><u>TestSimplePhysics.java</u></html>"><param name="textColor" value="blue"></object></div>
124 </li>
125 <li><div> <object classid="java:org.netbeans.modules.javahelp.BrowserDisplayer"><param name="content" value="http://code.google.com/p/jmonkeyengine/source/browse/trunk/engine/src/test/jme3test/bullet/TestWalkingChar.java"><param name="text" value="<html><u>TestWalkingChar.java</u></html>"><param name="textColor" value="blue"></object></div>
126 </li>
127 </ul>
128
129 </div>
130 <!-- EDIT3 SECTION "Sample Code" [5941-6540] -->
131 <h2><a>Physics Application</a></h2>
132 <div>
133
134 <p>
135
136 A short overview of how to write a jME application with Physics capabilities:
137 </p>
138
139 <p>
140 Do the following once per application to gain access to the <code>physicsSpace</code> object:
141 </p>
142 <ol>
143 <li><div> Make your application extend <code>com.jme3.app.SimpleApplication</code>.</div>
144 </li>
145 <li><div> Create a BulletAppState field: <pre>private BulletAppState bulletAppState;</pre>
146 </div>
147 </li>
148 <li><div> Initialize your bulletAppState and attach it to the state manager: <pre>public void simpleInitApp&#40;&#41; &#123;
149     bulletAppState = new BulletAppState&#40;&#41;;
150     stateManager.attach&#40;bulletAppState&#41;;</pre>
151 </div>
152 </li>
153 </ol>
154
155 <p>
156
157 <p><div>In your application, you can always access the <code>BulletAppState</code> via the ApplicationStateManager: 
158 </p>
159 <pre>BulletAppState bas = app.getStateManager&#40;&#41;.getState&#40;BulletAppState.class&#41;;</pre>
160
161 <p>
162
163 </div></p>
164 </p>
165
166 <p>
167 For each Spatial that you want to be physical:
168 </p>
169 <ol>
170 <li><div> Create a CollisionShape.</div>
171 </li>
172 <li><div> Create the PhysicsControl from the CollisionShape and a mass value.</div>
173 </li>
174 <li><div> Add the PhysicsControl to its Spatial.</div>
175 </li>
176 <li><div> Add the PhysicsControl to the PhysicsSpace.</div>
177 </li>
178 <li><div> Attach the Spatial to the rootNode (as usual).</div>
179 </li>
180 <li><div> (Optional) Implement the <code>PhysicsCollisionListener</code> interface to respond to <code>PhysicsCollisionEvent</code>s.</div>
181 </li>
182 </ol>
183
184 <p>
185
186 Let&#039;s look at the details: 
187 </p>
188
189 </div>
190 <!-- EDIT4 SECTION "Physics Application" [6541-7742] -->
191 <h2><a>Create a CollisionShape</a></h2>
192 <div>
193
194 <p>
195
196 A CollisionShape is a simplified shape for which physics are easier to calculate than for the true shape of the model. This simplication approach speeds up the simulation greatly.
197 </p>
198
199 <p>
200 Before you can create a Physics Control, you must create a CollisionShape from the <code>com.jme3.bullet.collision.shapes</code> package. (Read the tip under &quot;PhysicsControls Code Samples&quot; how to use default CollisionShapes for Boxes and Spheres.)
201
202 </p>
203 <div><table>
204         <tr>
205                 <th> Non-Mesh CollisionShape     </th><th> Usage                                </th><th> Examples </th>
206         </tr>
207         <tr>
208                 <td> BoxCollisionShape()         </td><td> Box-shaped behaviour, does not roll. </td><td> Oblong or cubic objects like bricks, crates, furniture.  </td>
209         </tr>
210         <tr>
211                 <td> SphereCollisionShape()      </td><td> Spherical behaviour, can roll.       </td><td> Compact objects like apples, soccer balls, cannon balls, compact spaceships. </td>
212         </tr>
213         <tr>
214                 <td> CylinderCollisionShape()    </td><td> Tube-shaped and disc-shaped behaviour, can roll on one side. </td><td> Oblong objects like pillars. <br/>
215 Disc-shaped objects like wheels, plates. </td>
216         </tr>
217         <tr>
218                 <td> CompoundCollisionShape()    </td><td> A CompoundCollisionShape allows custom combinations of shapes. Use the <code>addChildShape()</code> method on the compound object to add other shapes to it and position them relative to one another. </td><td> A car with wheels (1 box + 4 cylinders), etc. </td>
219         </tr>
220         <tr>
221                 <td> CapsuleCollisionShape()     </td><td> A built-in compound shape of a vertical cylinder with one sphere at the top and one sphere at the bottom. Typically used with <a href="/com/jme3/gde/docs/jme3/advanced/walking_character.html">CharacterControls</a>: A cylinder-shaped body does not get stuck at corners and vertical obstacles; the rounded top and bottom do not get stuck on stair steps and ground obstacles.  </td><td> Persons, animals. </td>
222         </tr>
223         <tr>
224                 <td> SimplexCollisionShape()     </td><td> A physical point, line, triangle, or rectangle Shape, defined by one to four points.</td><td>Guardrails</td>
225         </tr>
226         <tr>
227                 <td> PlaneCollisionShape()       </td><td> A 2D plane. Very fast. </td><td> Flat solid floor or wall. </td>
228         </tr>
229 </table></div>
230 <!-- EDIT6 TABLE [8201-9598] -->
231 <p>
232
233 All non-mesh CollisionShapes can be used for dynamic, kinematic, as well as static Spatials. (Code samples see below)
234
235 </p>
236 <div><table>
237         <tr>
238                 <th> Mesh CollisionShapes   </th><th> Usage                                </th><th> Examples </th>
239         </tr>
240         <tr>
241                 <td> MeshCollisionShape        </td><td> A mesh-accurate shape for static or kinematic Spatials. Can have complex shapes with openings and appendages. <br/>
242 <strong>Limitations:</strong> Collisions between two mesh-accurate shapes cannot be detected, only non-mesh shapes can collide with this shape. This Shape does not work with dynamic Spatials. </td><td> A whole static game level model. </td>
243         </tr>
244         <tr>
245                 <td> HullCollisionShape        </td><td> A less accurate shape for dynamic Spatials that cannot easily be represented by a CompoundShape. <br/>
246 <strong>Limitations:</strong> The shape is convex (behaves as if you gift-wrapped the object), i.e. openings, appendages, etc, are not individually represented. </td><td> A dynamic 3D model. </td>
247         </tr>
248         <tr>
249                 <td> GImpactCollisionShape     </td><td> A mesh-accurate shape for dynamic Spatials. It uses <object classid="java:org.netbeans.modules.javahelp.BrowserDisplayer"><param name="content" value="http://gimpact.sourceforge.net/"><param name="text" value="<html><u>http://gimpact.sourceforge.net/</u></html>"><param name="textColor" value="blue"></object>. <br/>
250 <strong>Limitations:</strong> CPU intensive, use sparingly! We recommend using HullCollisionShape (or CompoundShape) instead to improve performance. Collisions between two mesh-accurate shapes cannot be detected, only non-mesh shapes can collide with this shape. </td><td> Complex dynamic objects (like spiders) in Virtual Reality or scientific simulations. </td>
251         </tr>
252         <tr>
253                 <td> HeightfieldCollisionShape </td><td> A mesh-accurate shape optimized for static terrains. This shape is much faster than other mesh-accurate shapes. <br/>
254 <strong>Limitations:</strong> Requires heightmap data. Collisions between two mesh-accurate shapes cannot be detected, only non-mesh shapes can collide with this shape.</td><td>Static terrains.</td>
255         </tr>
256 </table></div>
257 <!-- EDIT7 TABLE [9719-11236] -->
258 <p>
259
260 On a CollisionShape, you can apply a few properties
261 </p>
262 <div><table>
263         <tr>
264                 <th> CollisionShape Method </th><th> Property </th><th> Examples </th>
265         </tr>
266         <tr>
267                 <td> setScale(new Vector3f(2f,2f,2f)) </td><td> You can change the scale of collisionshapes (whether it be, Simple or Mesh). You cannot change the scale of a CompoundCollisionShape however. A sphere collision shape, will change its radius based on the X component of the vector passed in. You must scale a collision shape before attaching it to the physicsSpace, or you must readd it to the physicsSpace each time the scale changes. </td><td> Scale a player in the Y axis by 2: <br/>
268 <code>new Vector3f(1f,2f,1f)</code></td>
269         </tr>
270 </table></div>
271 <!-- EDIT8 TABLE [11290-11827] -->
272 <p>
273
274 The mesh-accurate shapes can use a CollisionShapeFactory as constructor (code samples see below).
275 </p>
276
277 <p>
278 <p><div>Pick the simplest and most applicable shape for the mesh for what you want to do: If you give a box a sphere collision shape, it will roll; if you give a ball a box collision shape, it will sit on a slope. If the shape is too big, the object will seem to float; if the shape is too small it will seem to sink into the ground. During development and debugging, you can make collision shapes visible by adding the following line after the bulletAppState initialization: 
279 </p>
280 <pre>bulletAppState.getPhysicsSpace&#40;&#41;.enableDebug&#40;assetManager&#41;;</pre>
281
282 <p>
283
284 </div></p>
285 </p>
286
287 </div>
288 <!-- EDIT5 SECTION "Create a CollisionShape" [7743-12497] -->
289 <h3><a>CollisionShape Code Samples</a></h3>
290 <div>
291 <ul>
292 <li><div> One way of using a constructor and a Geometry&#039;s mesh for static Spatials:<pre>MeshCollisionShape level_shape = 
293     new MeshCollisionShape&#40;level_geo.getMesh&#40;&#41;&#41;;</pre>
294 </div>
295 </li>
296 <li><div> One way of using a constructor and a Geometry&#039;s mesh for dynamic Spatials:<pre>HullCollisionShape shape = 
297     new HullCollisionShape&#40;katamari_geo.getMesh&#40;&#41;&#41;;</pre>
298 </div>
299 </li>
300 <li><div> Creating a dynamic compound shape for a whole Node and subnodes:<pre>CompoundCollisionShape myComplexShape =
301     CollisionShapeFactory.createMeshShape&#40;&#40;Node&#41; myComplexGeometry &#41;;</pre>
302 </div>
303 </li>
304 <li><div> Creating a dynamic HullCollisionShape shape (or CompoundCollisionShape with HullCollisionShapes as children) for a Geometry:<pre>CollisionShape shape = 
305     CollisionShapeFactory.createDynamicMeshShape&#40;spaceCraft&#41;;</pre>
306 </div>
307 </li>
308 <li><div> An angular, non-mesh-accurate compound shape:<pre>CompoundCollisionShape boxShape =
309     CollisionShapeFactory.createBoxCompoundShape&#40;&#40;Node&#41; crate_geo&#41;;</pre>
310 </div>
311 </li>
312 <li><div> A round, non-mesh-accurate compound shape: <pre>SphereCollisionShape sphereShape =
313     new SphereCollisionShape&#40;1.0f&#41;;</pre>
314 </div>
315 </li>
316 </ul>
317
318 </div>
319 <!-- EDIT9 SECTION "CollisionShape Code Samples" [12498-13624] -->
320 <h2><a>Create PhysicsControl</a></h2>
321 <div>
322
323 <p>
324
325 BulletPhysics are available in jME3 through PhysicsControls classes from the com.jme3.bullet.control package. jME3&#039;s PhysicsControl classes directly extend BulletPhysics objects and are the recommended way to use physics in a jME3 application. PhysicsControls are flexible and can be added to any Spatial to make it act according to physical properties. 
326
327 </p>
328 <div><table>
329         <tr>
330                 <th>Standard PhysicsControls</th><th> Usage</th><th> Examples </th>
331         </tr>
332         <tr>
333                 <td>RigidBodyControl</td><td>The most commonly used PhysicsControl. You can use it for dynamic objects (solid objects that freely affected by collisions, forces, or gravity), for static objects (solid but not affected by any forces), or kinematic objects (remote-controlled solid objects). </td><td>Impacting projectiles, moving obstacles like crates, rolling and bouncing balls, elevators, flying aircaft or space ships. <br/>
334 Solid immobile floors, walls, static obstacles.</td>
335         </tr>
336         <tr>
337                 <td>GhostControl</td><td>Use for collision and intersection detection between physical objects. A GhostControl itself is <em>non-solid</em> and invisible. GhostControl moves with the Spatial it is attached to. Use GhostControls to <a href="/com/jme3/gde/docs/jme3/advanced/physics_listeners.html">implement custom game interactions</a> by adding it to a visible Geometry. </td><td>A monster&#039;s &quot;aggro radius&quot;, CharacterControl collisions, motion detectors, photo-electric alarm sensors, poisonous or radioactive perimeters, life-draining ghosts, etc. </td>
338         </tr>
339 </table></div>
340 <!-- EDIT11 TABLE [14016-14995] --><div><table>
341         <tr>
342                 <th>Special PhysicsControls</th><th> Usage</th><th> Examples </th>
343         </tr>
344         <tr>
345                 <td>VehicleControl <br/>
346 PhysicsVehicleWheel</td><td> Special Control used for <a href="/com/jme3/gde/docs/jme3/advanced/vehicles.html">&quot;terrestrial&quot;  vehicles with suspension and wheels</a>. </td><td>Cars, tanks, hover crafts, ships, motorcycles???</td>
347         </tr>
348         <tr>
349                 <td>CharacterControl</td><td>Special Control used for <a href="/com/jme3/gde/docs/jme3/advanced/walking_character.html">Walking Character</a>s.</td><td>Upright walking persons, animals, robots??? </td>
350         </tr>
351         <tr>
352                 <td>RagDollControl</td><td>Special Control used for <a href="/com/jme3/gde/docs/jme3/advanced/ragdoll.html">collapsing, flailing, or falling characters</a> </td><td>Falling persons, animals, robots, &quot;Rag dolls&quot;</td>
353         </tr>
354 </table></div>
355 <!-- EDIT12 TABLE [14997-15509] -->
356 <p>
357
358 Click the links for details on the special PhysicsControls. This article is about RigidBodyControl.
359 </p>
360
361 </div>
362 <!-- EDIT10 SECTION "Create PhysicsControl" [13625-15611] -->
363 <h3><a>PhysicsControls Code Samples</a></h3>
364 <div>
365
366 <p>
367
368 The PhysicsControl constructors expect a Collision Shape and a mass (a float in kilogram). The most commonly used PhysicsControl is the RigidBodyControl:
369 </p>
370 <pre>RigidBodyControl myThing_phys = 
371     new RigidBodyControl&#40; myThing_shape , 123.0f &#41;; // dynamic</pre>
372 <pre>RigidBodyControl myDungeon_phys = 
373     new RigidBodyControl&#40; myDungeon_shape , 0.0f &#41;; // static </pre>
374
375 <p>
376 <p><div>When you create the PhysicsControl, the mass value makes an important distinction: Set the mass to a non-zero value to create a dynamic object that can fall or roll, etc. Set the mass value to zero to create a static object, such as floor, wall, etc. If you give your floor a mass, it will fall out of the scene! 
377 </div></p>
378 </p>
379
380 <p>
381 The following creates a box Geometry with the correct default BoxCollisionShape:
382 </p>
383 <pre>Box b = new Box&#40;1,1,1&#41;;
384 Geometry box_geo = new Geometry&#40;&quot;Box&quot;, b&#41;;
385 box_geo.addControl&#40;new RigidBodyControl&#40; 1.0f &#41;&#41;; // explicit non-zero mass, implicit BoxCollisionShape</pre>
386
387 <p>
388
389 The following creates a MeshCollisionShape for a whole loaded (static) scene:
390
391 </p>
392 <pre>...
393 gameLevel.addControl&#40;new RigidBodyControl&#40;0.0f&#41;&#41;; // explicit zero mass, implicit MeshCollisionShape</pre>
394
395 <p>
396 <p><div>Spheres and Boxes automatically fall back on the correct default CollisionShape if you do not specify a CollisionShape in the RigidBodyControl constructor. Complex static objects can fall back on MeshCollisionShapes, unless it is a Node, in which case it will become a CompoundCollisionShape containing a MeshCollisionShape
397 </div></p>
398 </p>
399
400 </div>
401 <!-- EDIT13 SECTION "PhysicsControls Code Samples" [15612-17191] -->
402 <h2><a>Add PhysicsControl to Spatial</a></h2>
403 <div>
404
405 <p>
406
407 For each physical Spatial in the scene:
408 </p>
409 <ol>
410 <li><div> Add a PhysicsControl to a Spatial. <pre>myThing_geo.addControl&#40;myThing_phys&#41;;</pre>
411 </div>
412 </li>
413 <li><div> Remember to also attach the Spatial to the rootNode, as always!</div>
414 </li>
415 </ol>
416
417 </div>
418 <!-- EDIT14 SECTION "Add PhysicsControl to Spatial" [17192-17439] -->
419 <h2><a>Add PhysicsControl to PhysicsSpace</a></h2>
420 <div>
421
422 <p>
423
424 The PhysicsSpace is an object in BulletAppState that is like a rootNode for Physics Controls. 
425
426 </p>
427 <ul>
428 <li><div> Just like you add the Geometry to the rootNode, you add its PhysicsControl to the PhysicsSpace. <pre>bulletAppState.getPhysicsSpace&#40;&#41;.add&#40;myThing_phys&#41;; 
429 rootNode.attachChild&#40;myThing_geo&#41;; </pre>
430 </div>
431 </li>
432 <li><div> When you remove a Geometry from the scene and detach it from the rootNode, also remove the PhysicsControl from the PhysicsSpace: <pre>bulletAppState.getPhysicsSpace&#40;&#41;.remove&#40;myThing_phys&#41;;
433 myThing_geo.removeFromParent&#40;&#41;;</pre>
434 </div>
435 </li>
436 </ul>
437
438 <p>
439
440 <p><div>You can either add the <em>PhysicsControl</em> to the PhysicsSpace, or add the PhysicsControl to the Geometry and then add the <em>Geometry</em> to the PhysicsSpace. jME3 understands both and the outcome is the same.
441 </div></p>
442 </p>
443
444 </div>
445 <!-- EDIT15 SECTION "Add PhysicsControl to PhysicsSpace" [17440-18255] -->
446 <h2><a>Changing the Scale of a PhysicsControl</a></h2>
447 <div>
448
449 <p>
450 To change the scale of a PhysicsControl you must change the scale of the collisionshape which belongs to it.
451 </p>
452
453 <p>
454 MeshCollisionShapes can have a scale correctly set, but it only works when being constructed on a geometry (not a node). CompoundCollisionShapes cannot be scaled at this time(the type obtained when creating a CollisionShape from a Node i.e using imported models).
455 </p>
456
457 <p>
458 When you import a model from blender, it often comes as a Node (even if it only contains 1 mesh), which is by de-facto automatically converted to a CompoundCollisionShape. So when you try to scale this it won&#039;t work! Below illustrates an example, of how to scale an imported model:
459 </p>
460 <pre>// Doesn't scale
461 // This modified version contains Node -&gt; Geometry (name = &quot;MonkeyHeadGeom&quot;)
462 Spatial model = assetManager.loadModel&#40;&quot;Models/MonkeyHead.j3o&quot;&#41;; model.addControl&#40;new RigidBodyControl&#40;0&#41;&#41;;
463 // Won't work as this is now a CompoundCollisionShape containing a MeshCollisionShape
464 model.getControl&#40;RigidBodyControl.class&#41;.getCollisionShape&#40;&#41;.setScale&#40;new Vector3f&#40;2, 2, 2&#41;&#41;; 
465 bulletAppState.getPhysicsSpace&#40;&#41;.add&#40;model&#41;;
466 &nbsp;
467 // Works fine
468 Spatial model = assetManager.loadModel&#40;&quot;Models/MonkeyHead.j3o&quot;&#41;; // Same Model
469  // IMPORTANT : You must navigate to the Geometry for this to work
470 Geometry geom = &#40;&#40;Geometry&#41; &#40;&#40;Node&#41; model&#41;.getChild&#40;&quot;MonkeyHeadGeom&quot;&#41;&#41;;
471 geom.addControl&#40;new RigidBodyControl&#40;0&#41;&#41;;
472 // Works great (scaling of a MeshCollisionShape)        
473 geom.getControl&#40;RigidBodyControl.class&#41;.getCollisionShape&#40;&#41;.setScale&#40;new Vector3f&#40;2, 2, 2&#41;&#41;;
474 bulletAppState.getPhysicsSpace&#40;&#41;.add&#40;geom&#41;;</pre>
475
476 <p>
477 With the corresponding output below:
478 <object classid="java:org.netbeans.modules.javahelp.BrowserDisplayer"><param name="content" value="http://i.imgur.com/fAXlF.png"><param name="text" value="<html><u>External Link</u></html>"><param name="textColor" value="blue"></object>
479 <object classid="java:org.netbeans.modules.javahelp.BrowserDisplayer"><param name="content" value="http://i.imgur.com/Josua.png"><param name="text" value="<html><u>External Link</u></html>"><param name="textColor" value="blue"></object>
480
481 </p>
482
483 </div>
484 <!-- EDIT16 SECTION "Changing the Scale of a PhysicsControl" [18256-20006] -->
485 <h3><a>PhysicsSpace Code Samples</a></h3>
486 <div>
487
488 <p>
489
490 The PhysicsSpace also manages global physics settings. Typically, you can leave the defaults, and you don&#039;t need to change the following settings, but it&#039;s good to know what they are for:
491
492 </p>
493 <div><table>
494         <tr>
495                 <th>bulletAppState.getPhysicsSpace() Method</th><th>Usage</th>
496         </tr>
497         <tr>
498                 <td>setGravity(new Vector3f(0, -9.81f, 0));</td><td>Specifies the global gravity.</td>
499         </tr>
500         <tr>
501                 <td>setAccuracy(1f/60f);</td><td>Specifies physics accuracy. The higher the accuracy, the slower the game. Increase value if objects are passing through one another, or bounce oddly.</td>
502         </tr>
503         <tr>
504                 <td>setMaxSubSteps(4);</td><td>Compensates low FPS: Specifies the maximum amount of extra steps that will be used to step the physics when the game fps is below the physics fps. This maintains determinism in physics in slow (low-fps) games. For example a maximum number of 2 can compensate for framerates as low as 30 fps (physics has a default accuracy of 60 fps). Note that setting this value too high can make the physics drive down its own fps in case its overloaded.</td>
505         </tr>
506         <tr>
507                 <td>setWorldMax(new Vector3f(10000f, 10000f, 10000f)); <br/>
508 setWorldMin(new Vector3f(-10000f, -10000f, -10000f));</td><td>Specifies the size of the physics space as two opposite corners (only applies to AXIS_SWEEP broadphase).</td>
509         </tr>
510         <tr>
511                 <td>setCcdMotionThreshold()</td><td>The amount of motion in 1 physics tick to trigger the continuous motion detection in moving objects that push one another. Rarely used, but necessary if your moving objects get stuck or roll through one another.</td>
512         </tr>
513 </table></div>
514 <!-- EDIT18 TABLE [20233-21440] -->
515 </div>
516 <!-- EDIT17 SECTION "PhysicsSpace Code Samples" [20007-21441] -->
517 <h2><a>Specify Physical Properties</a></h2>
518 <div>
519
520 <p>
521
522 After you have registered, attached, and added everything, you can adjust physical properties or apply forces.
523 </p>
524
525 <p>
526 On a RigidBodyControl, you can set the following physical properties.
527
528 </p>
529 <div><table>
530         <tr>
531                 <th> RigidBodyControl Method </th><th> Property </th><th> Examples </th>
532         </tr>
533         <tr>
534                 <td> setGravity(new Vector3f(0f,-9.81f,0f)) </td><td> You can change the gravity of individual physics objects after they were added to the PhysicsSpace. Gravity is a vector pointing from this Spatial towards the source of gravity. The longer the vector, the stronger is gravity. <br/>
535 If gravity is the same absolute direction for all objects (e.g. on a planet surface), set this vector globally on the PhysicsSpace object and not individually. <br/>
536 If the center of gravity is relative (e.g. towards a black hole) then setGravity() on each Spatial to constantly adjust the gravity vectors at each tick of their update() loops.</td><td>For planet earth: <br/>
537 <code>new Vector3f(0f,-9.81f,0f)</code></td>
538         </tr>
539         <tr>
540                 <td> setMass(1f) </td><td> Sets the mass in kilogram. Dynamic objects have masses &gt; 0.0f. Heavy dynamic objects need more force to be moved and light ones move with small amounts of force. <br/>
541 Static immobile objects (walls, floors, including buildings and terrains) must have a mass of zero! </td><td> Person: 60f, ball: 1.0f <br/>
542 Floor: 0.0f (!)</td>
543         </tr>
544         <tr>
545                 <td> setFriction(1f) </td><td> Friction. <br/>
546 Slippery objects have low friction. The ground has high friction. </td><td> Ice, slides: 0.0f <br/>
547 Soil, concrete, rock: 1.0f </td>
548         </tr>
549         <tr>
550                 <td> setRestitution(0.0f) </td><td> Bounciness. By default objects are not bouncy (0.0f). For a bouncy rubber object set this &gt; 0.0f. <br/>
551 Both the object and the surface must have non-zero restitution for bouncing to occur. <br/>
552 This setting has an impact on performance, so use it sparingly. </td><td> Brick: 0.0f <br/>
553 Rubber ball: 1.0f </td>
554         </tr>
555 </table></div>
556 <!-- EDIT20 TABLE [21666-23176] -->
557 <p>
558
559 On a RigidBodyControl, you can apply the following physical forces:
560
561 </p>
562 <div><table>
563         <tr>
564                 <th> RigidBodyControl Method </th><th> Motion </th>
565         </tr>
566         <tr>
567                 <td> setPhysicsLocation()</td><td>Positions the objects. Do not use setLocalTranslation() for physical objects. Important: Make certain not to make CollisionShapes overlap when positioning them. </td>
568         </tr>
569         <tr>
570                 <td> setPhysicsRotation()</td><td>Rotates the object. Do not use setLocalRotate() for physical objects.</td>
571         </tr>
572         <tr>
573                 <td> setKinematic(true) </td><td> By default, RigidBodyControls are dynamic (kinematic=false) and are affected by forces. If you set kinematic=true, the object is no longer affected by forces, but it still affects others. A kinematic is solid, and must have a mass. <br/>
574 (See detailed explanation below.) </td>
575         </tr>
576 </table></div>
577 <!-- EDIT21 TABLE [23247-23857] -->
578 </div>
579 <!-- EDIT19 SECTION "Specify Physical Properties" [21442-23857] -->
580 <h3><a>Kinematic vs Dynamic vs Static</a></h3>
581 <div>
582
583 <p>
584
585 All physical objects???
586 </p>
587 <ul>
588 <li><div> must not overlap. </div>
589 </li>
590 <li><div> can detect collisions and report several values about the impact.</div>
591 </li>
592 <li><div> can respond to collisions dynamically, or statically, or kinematically.</div>
593 </li>
594 </ul>
595 <div><table>
596         <tr>
597                 <td> Property </td><th> Static </th><th> Kinematic </th><th> Dynamic </th>
598         </tr>
599         <tr>
600                 <th> Examples</th><td>Immobile obstacles: Floors, walls, buildings, ???</td><td>Remote-controlled solid objects: Airships, meteorites, elevators, doors; networked or remote-controlled NPCs; invisible &quot;airhooks&quot; for hinges and joints.</td><td>Interactive objects: Rolling balls, movable crates, falling pillars, zero-g space ship???</td>
601         </tr>
602         <tr>
603                 <th> Does it have a mass?</th><td>no, 0.0f</td><td>yes<sup><a href="#fn__1">1)</a></sup>, &gt;0.0f </td><td>yes, &gt;0.0f</td>
604         </tr>
605         <tr>
606                 <th> How does it move?</th><td>never</td><td>setLocalTranslation();</td><td>setLinearVelocity(); applyForce(); <br/>
607 setWalkDirection(); for CharacterControl</td>
608         </tr>
609         <tr>
610                 <th> How to place in scene?</th><td>setPhysicsLocation(); <br/>
611 setPhysicsRotation()</td><td>setLocalTranslation(); <br/>
612 setLocalRotation();</td><td>setPhysicsLocation(); <br/>
613  setPhysicsRotation()</td>
614         </tr>
615         <tr>
616                 <th> Can it move and push others?</th><td>no</td><td>yes</td><td>yes</td>
617         </tr>
618         <tr>
619                 <th> Is is affected by forces? <br/>
620 (Falls when it mid-air? Can be pushed by others?)</th><td>no</td><td>no</td><td>yes</td>
621         </tr>
622         <tr>
623                 <th> How to activate this behaviour? </th><td>setMass(0f); <br/>
624 setKinematic(false); </td><td>setMass(1f); <br/>
625 setKinematic(true);</td><td>setMass(1f); <br/>
626 setKinematic(false);</td>
627         </tr>
628 </table></div>
629 <!-- EDIT23 TABLE [24094-25153] -->
630 </div>
631
632 <h4><a>When Do I Use Kinematic Objects?</a></h4>
633 <div>
634 <ul>
635 <li><div> Kinematics are solid and characters can &quot;stand&quot; on them.</div>
636 </li>
637 <li><div> When they collide, Kinematics push dynamic objects, but a dynamic object never pushes a Kinematic. </div>
638 </li>
639 <li><div> You can hang kinematics up &quot;in mid-air&quot; and attach other PhysicsControls to them using <a href="/com/jme3/gde/docs/jme3/advanced/hinges_and_joints.html">hinges and joints</a>. Picture them as &quot;air hooks&quot; for flying aircraft carriers, floating islands in the clouds, suspension bridges, swings, chains??? </div>
640 </li>
641 <li><div> You can use Kinematics to create mobile remote-controlled physical objects, such as moving elevator platforms, flying blimps/airships. You have full control how Kinematics move, they never &quot;fall&quot; or &quot;topple over&quot;.</div>
642 </li>
643 </ul>
644
645 <p>
646
647 <p><div>The position of a kinematic RigidBodyControl is updated automatically depending on its spatial&#039;s translation. You move Spatials with a kinematic RigidBodyControl programmatically, that means you write translation and rotation code in the update loop. You describe the motion of kinematic objects either by using methods such as <code>setLocalTranslation()</code> or <code>move()</code>, or by using a <a href="/com/jme3/gde/docs/jme3/advanced/motionpath.html">MotionPath</a>. 
648 </div></p>
649 </p>
650
651 </div>
652 <!-- EDIT22 SECTION "Kinematic vs Dynamic vs Static" [23858-26259] -->
653 <h2><a>Forces: Moving Dynamic Objects</a></h2>
654 <div>
655
656 <p>
657
658 Use the following methods to move dynamic physical objects.
659
660 </p>
661 <div><table>
662         <tr>
663                 <th> PhysicsControl Method </th><th> Motion </th>
664         </tr>
665         <tr>
666                 <td> setLinearVelocity(new Vector3f(0f,0f,1f)) </td><td> Set the linear speed of this object. </td>
667         </tr>
668         <tr>
669                 <td> setAngularVelocity(new Vector3f(0f,0f,1f)) </td><td> Set the rotational speed of the object; the x, y and z component are the speed of rotation around that axis. </td>
670         </tr>
671         <tr>
672                 <td> applyCentralForce(???) </td><td> Move (push) the object once with a certain moment, expressed as a Vector3f.  </td>
673         </tr>
674         <tr>
675                 <td> applyForce(???) </td><td> Move (push) the object once with a certain moment, expressed as a Vector3f. Optionally, you can specify where on the object the pushing force hits. </td>
676         </tr>
677         <tr>
678                 <td> applyTorque(???) </td><td> Rotate (twist) the object once around its axes, expressed as a Vector3f. </td>
679         </tr>
680         <tr>
681                 <td> applyImpulse(???) </td><td> An idealised change of momentum. This is the kind of push that you would use on a pool billiard ball. </td>
682         </tr>
683         <tr>
684                 <td> applyTorqueImpulse(???) </td><td> An idealised change of momentum. This is the kind of push that you would use on a pool billiard ball. </td>
685         </tr>
686         <tr>
687                 <td> clearForces()</td><td>Cancels out all forces (force, torque) etc and stops the motion.</td>
688         </tr>
689 </table></div>
690 <!-- EDIT25 TABLE [26365-27354] -->
691 <p>
692
693 <p><div>It is technically possible to position PhysicsControls using setLocalTranslation(), e.g. to place them in their start position in the scene. However you must be very careful not to cause an &quot;impossible state&quot; where one physical object overlaps with another! Within the game, you typically use the setters shown here exclusively.
694 </div></p>
695 </p>
696
697 <p>
698 PhysicsControls also support the following advanced features:
699
700 </p>
701 <div><table>
702         <tr>
703                 <th> PhysicsControl Method </th><th> Property </th>
704         </tr>
705         <tr>
706                 <td> setCollisionShape(collisionShape)</td><td>Changes the collision shape after creation.</td>
707         </tr>
708         <tr>
709                 <td> setCollideWithGroups() <br/>
710 setCollisionGroup() <br/>
711 addCollideWithGroup(COLLISION_GROUP_01) <br/>
712 removeCollideWithGroup(COLLISION_GROUP_01)</td><td>Collision Groups are integer bit masks ??? enums are available in the CollisionObject. All physics objects are by default in COLLISION_GROUP_01. Two objects collide when the collideWithGroups set of one contains the Collision Group of the other. Use this to improve performance by grouping objects that will never collide in different groups (the the engine saves times because it does not need to check on them).</td>
713         </tr>
714         <tr>
715                 <td> setDamping(float, float)</td><td>The first value is the linear threshold and the second the angular. This simulates dampening of forces, for example for underwater scenes.</td>
716         </tr>
717         <tr>
718                 <td> setAngularFactor(1f)</td><td>Set the amount of rotation that will be applied. A value of zero will cancel all rotational force outcome. (?)</td>
719         </tr>
720         <tr>
721                 <td> setSleepingThreshold(float,float)</td><td>Sets the sleeping thresholds which define when the object gets deactivated to save resources. The first value is the linear threshold and the second the angular. Low values keep the object active when it barely moves (slow precise performance), high values put the object to sleep immediately (imprecise fast performance). (?) </td>
722         </tr>
723         <tr>
724                 <td> setCcdMotionThreshold(0f) </td><td>Sets the amount of motion that has to happen in one physics tick to trigger the continuous motion detection in moving objects that push one another. This avoids the problem of fast objects moving through other objects. Set to zero to disable (default).</td>
725         </tr>
726         <tr>
727                 <td> setCcdSweptSphereRadius(.5f)</td><td>Bullet does not use the full collision shape for continuous collision detection, instead it uses a &quot;swept sphere&quot; shape to approximate a motion, which can be imprecise and cause strange behaviors such as objects passing through one another or getting stuck. Only relevant for fast moving dynamic bodies. </td>
728         </tr>
729 </table></div>
730 <!-- EDIT26 TABLE [27772-29727] -->
731 <p>
732
733 <p><div> You can <code>setApplyPhysicsLocal(true)</code> for an object to make it move relatively to its local physics space. You would do that if you need a physics space that moves with a node (e.g. a spaceship with artificial gravity surrounded by zero-g space). By default, it&#039;s set to false, and all movement is relative to the world.
734 </div></p>
735 </p>
736
737 </div>
738 <!-- EDIT24 SECTION "Forces: Moving Dynamic Objects" [26260-30069] -->
739 <h2><a>Best Practices</a></h2>
740 <div>
741 <ul>
742 <li><div> <strong>Multiple Objects Too Slow?</strong> Do not overuse PhysicsControls. Although PhysicsControls are put to ???sleep??? when they are not moving, creating a world solely out of dynamic physics objects will quickly bring you to the limits of your computer&#039;s capabilities. <br/>
743 <strong>Solution:</strong> Improve performance by replacing some physical Spatials with non-physical Spatials. Use the non-physical ones for non-solid things for which you do not need to detect collisions ??? foliage, plants, effects, ghosts, all remote or unreachable objects.</div>
744 </li>
745 </ul>
746 <ul>
747 <li><div> <strong>Complex Shape Too Slow?</strong> Breaking the level into manageable pieces helps the engine improve performance: The less CPU-intensive <object classid="java:org.netbeans.modules.javahelp.BrowserDisplayer"><param name="content" value="http://en.wikipedia.org/wiki/Sweep_and_prune"><param name="text" value="<html><u>broadphase</u></html>"><param name="textColor" value="blue"></object> filters out parts of the scene that are out of reach. It only calculates the collisions for objects that are actually close to the action. <br/>
748 <strong>Solution:</strong> A huge static city or terrain model should never be loaded as one huge mesh. Divide the scene into multiple physics objects, with each its own CollisionShape. Choose the most simple CollisionShape possible; use mesh-accurate shapes only for the few cases where precision is more important than speed. For example, you can use the very fast <code>PlaneCollisionShape</code> for flat streets, floors and the outside edge of the scene, if you keep these pieces separate.</div>
749 </li>
750 </ul>
751 <ul>
752 <li><div> <strong>Eject?</strong> If you have physical nodes jittering wildy and being ejected &quot;for no apparent reason&quot;, it means you have created an impossible state ??? solid objects overlapping. This can happen when you position solid spatials too close to other solid spatials, e.g. when moving them with setLocalTranslation(). <br/>
753 <strong>Solution:</strong> Use the debug mode to make CollisionShapes visible and verify that CollisionShapes do not overlap. <pre>bulletAppState.getPhysicsSpace&#40;&#41;.enableDebug&#40;assetManager&#41;;</pre>
754 </div>
755 </li>
756 </ul>
757 <ul>
758 <li><div> <strong>Buggy?</strong> If you get weird behaviour, such as physical nodes passing through one another, or getting stuck for no reason. <br/>
759 <strong>Solution:</strong> Look at the physics space accessors and change the acuracy and other parameters.</div>
760 </li>
761 </ul>
762 <ul>
763 <li><div> <strong>Need more interactivity?</strong> You can actively <em>control</em> a physical game by triggering forces. You may also want to be able <em>respond</em> to collisions, e.g. by substracting health, awarding points, or by playing a sound. <br/>
764 <strong>Solution:</strong> To specify how the game responds to collisions, you use <a href="/com/jme3/gde/docs/jme3/advanced/physics_listeners.html">Physics Listeners</a>.</div>
765 </li>
766 </ul>
767 <div><span>
768         <a href="/wiki/doku.php/tag:physics?do=showtag&amp;tag=tag%3Aphysics">physics</a>,
769         <a href="/wiki/doku.php/tag:documentation?do=showtag&amp;tag=tag%3Adocumentation">documentation</a>,
770         <a href="/wiki/doku.php/tag:control?do=showtag&amp;tag=tag%3Acontrol">control</a>
771 </span></div>
772
773 </div>
774 <!-- EDIT27 SECTION "Best Practices" [30070-] --><div>
775 <div><sup><a href="#fnt__1">1)</a></sup> 
776 Inertia is calculated for kinematic objects, and you need mass to do that.</div>
777 </div>
778 <p><em><a href="http://hub.jmonkeyengine.org/wiki/doku.php/jme3:advanced:physics?do=export_xhtmlbody">view online version</a></em></p>