custom_controls.adoc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. = Custom Controls
  2. :author:
  3. :revnumber:
  4. :revdate: 2016/03/17 20:48
  5. :relfileprefix: ../../
  6. :imagesdir: ../..
  7. ifdef::env-github,env-browser[:outfilesuffix: .adoc]
  8. A `com.jme3.scene.control.Control` is a customizable jME3 interface that allows you to cleanly steer the behaviour of game entities (Spatials), such as artificially intelligent behaviour in NPCs, traps, automatic alarms and doors, animals and pets, self-steering vehicles or platforms – anything that moves and interacts. Several instances of custom Controls together implement the behaviours of a type of Spatial.
  9. To control global game behaviour see <<jme3/advanced/application_states#,Application States>> – you often use AppStates and Control together.
  10. * link:http://www.youtube.com/watch?v=MNDiZ9YHIpM[Quick video introduction to Custom Controls]
  11. To control the behaviour of spatials:
  12. . Create one control for each _type of behavior_. When you add several controls to one spatial, they will be executed in the order they were added.
  13. +
  14. For example, one NPC can be controlled by a PhysicsControl instance and an AIControl instance.
  15. . Define the custom control and implement its behaviour in the Control's update method:
  16. ** You can pass arguments into your custom control.
  17. ** In the control class, the object `spatial` gives you access to the spatial and subspatials that the control is attached to.
  18. ** Here you modify the `spatial's` transformation (move, scale, rotate), play animations, check its environement, define how it acts and reacts.
  19. . Add an instance of the Control to a spatial to give it this behavior. The spatial's game state is updated automatically from now on.
  20. [source,java]
  21. ----
  22. spatial.addControl(myControl);
  23. ----
  24. To implement game logic for a type of spatial, you will either extend AbstractControl (most common case), or implement the Control interface, as explained in this article.
  25. == Usage
  26. Use <<jme3/advanced/custom_controls#,Controls>> to implement the _behaviour of types of game entities_.
  27. * Use Controls to add a type of behaviour (that is, methods and fields) to individual Spatials.
  28. * Each Control has its own `update()` loop that hooks into `simpleUpdate()`. Use Controls to move blocks of code out of the `simpleUpdate()` loop.
  29. * One Spatial can be influenced by several Controls. (Very powerful and modular!)
  30. * Each Spatial needs its own instance of the Control.
  31. * A Control only has access to and control over the Spatial it is attached to.
  32. * Controls can be saved as .j3o file together with a Spatial.
  33. Examples: You can write
  34. * A WalkerNavControl, SwimmerNavControl, FlyerNavControl… that defines how a type of NPC finds their way around. All NPCs can walk, some can fly, others can swim, and some can all three, etc.
  35. * A PlayerNavControl that is steered by user-configurable keyboard and mouse input.
  36. * A generic animation control that acts as a common interface that triggers animations (walk, stand, attack, defend) for various entities.
  37. * A DefensiveBehaviourControl that remote-controls NPC behaviour in fight situations.
  38. * An IdleBehaviourControl that remote-controls NPC behaviour in neutral situations.
  39. * A DestructionControl that automatically replaces a structure with an appropriate piece of debris after collision with a projectile…
  40. The possibilities are endless. icon:smiley[]
  41. == Example Code
  42. Other examples include the built-in RigidBodyControl in JME's physics integration, the built-in TerrainLODControl that updates the terrain's level of detail depending on the viewer's perspective, etc.
  43. Existing examples in the code base include:
  44. * link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-core/src/main/java/com/jme3/animation/AnimControl.java[AnimControl.java] allows manipulation of skeletal animation, including blending and multiple channels.
  45. * link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-core/src/main/java/com/jme3/scene/control/CameraControl.java[CameraControl.java] allows you to sync the camera position with the position of a given spatial.
  46. * link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-core/src/main/java/com/jme3/scene/control/BillboardControl.java[BillboardControl.java] displays a flat picture orthogonally, e.g. a speech bubble or informational dialog.
  47. * link:https://github.com/jMonkeyEngine/jmonkeyengine/tree/master/jme3-bullet/src/common/java/com/jme3/bullet/control[PhysicsControl] subclasses (such as CharacterControl, RigidBodyControl, VehicleControl) allow you to add physical properties to any spatial. PhysicsControls tie into capabilities provided by the BulletAppState.
  48. == AbstractControl Class
  49. [TIP]
  50. ====
  51. The most common way to create a Control is to create a class that extends AbstractControl.
  52. ====
  53. The AbstractControl can be found under `com.jme3.scene.control.AbstractControl`. This is a default abstract class that implements the Control interface.
  54. * You have access to a boolean `isEnabled()`.
  55. * You have access to the Spatial object `spatial`.
  56. * You override the `controlUpdate()` method to implement the Spatial's behaviour.
  57. * You have access to a `setEnabled(boolean)` method. This activates or deactivates this Control's behaviour in this spatial temporarily. While the AbstractControl is toggled to be disabled, the `controlUpdate()` loop is no longer executed.
  58. +
  59. For example, you disable your IdleBehaviourControl when you enable your DefensiveBehaviourControl in a spatial.
  60. Usage: Your custom subclass implements the three methods `controlUpdate()`, `controlRender()`, `setSpatial()`, and `cloneForSpatial()` as shown here:
  61. [source,java]
  62. ----
  63. public class MyControl extends AbstractControl implements Savable, Cloneable { 
  64. private int index; // can have custom fields -- example    
  65. public MyControl(){} // empty serialization constructor   
  66. /** Optional custom constructor with arguments that can init custom fields.   
  67. * Note: you cannot modify the spatial here yet!
  68. */ 
  69. public MyControl(int i){    
  70. // index=i; // example  
  71. }    
  72. /** This method is called when the control is added to the spatial,   
  73. * and when the control is removed from the spatial (setting a null value).   
  74. * It can be used for both initialization and cleanup.
  75. */     
  76. @Override 
  77. public void setSpatial(Spatial spatial) {   
  78. super.setSpatial(spatial);   
  79. /* Example:   
  80. if (spatial != null){       
  81. // initialize   
  82. }else{       
  83. // cleanup   
  84. }   
  85. */ 
  86. }
  87.  
  88. /** Implement your spatial's behaviour here.   
  89. * From here you can modify the scene graph and the spatial   
  90. * (transform them, get and set userdata, etc).   
  91. * This loop controls the spatial while the Control is enabled.
  92. */ 
  93. @Override 
  94. protected void controlUpdate(float tpf){   
  95. if(spatial != null) {     
  96. // spatial.rotate(tpf,tpf,tpf); // example behaviour   
  97. }   
  98. @Override 
  99. public Control cloneForSpatial(Spatial spatial){   
  100. final MyControl control = new MyControl();   
  101. /* Optional: use setters to copy userdata into the cloned control */   
  102. // control.setIndex(i); // example   
  103. control.setSpatial(spatial);   
  104. return control; 
  105. }   
  106. @Override 
  107. protected void controlRender(RenderManager rm, ViewPort vp){    
  108. /* Optional: rendering manipulation (for advanced users) */ 
  109. }   
  110. @Override 
  111. public void read(JmeImporter im) throws IOException {     
  112. super.read(im);     
  113. // im.getCapsule(this).read(...); 
  114. }   
  115. @Override 
  116. public void write(JmeExporter ex) throws IOException {     
  117. super.write(ex);     
  118. // ex.getCapsule(this).write(...); 
  119. }
  120. ----
  121. See also:
  122. * To learn more about `write()` and `read()`, see <<jme3/advanced/save_and_load#,Save and Load>>
  123. * To learn more about `setUserData()`, see <<jme3/advanced/spatial#,Spatial>>.
  124. == The Control Interface
  125. [TIP]
  126. ====
  127. In the less common case that you want to create a Control that also extends another class, create a custom interface that  extends jME3's Control interface. Your class can become a Control by implementing the Control interface, and at the same time extending another class.
  128. ====
  129. The Control interface can be found under `com.jme3.scene.control.Control`. It has the following method signatures:
  130. * `cloneForSpatial(Spatial)`: Clones the Control and attaches it to a clone of the given Spatial.
  131. +
  132. Implement this method to be able to <<jme3/advanced/save_and_load#,save() and load()>> Spatials carrying this Control.
  133. +
  134. The AssetManager also uses this method if the same spatial is loaded twice. You can specify which fields you want your object to reuse (e.g. collisionshapes) in this case.
  135. * `setEnabled(boolean)`: Toggles a boolean that enables or disables the Control. Goes with accessor `isEnabled();`. You test for it in the `update(float tpf)` loop before you execute anything.
  136. * There are also some internal methods that you do not call from user code: `setSpatial(Spatial s)`, `update(float tpf);`, `render(RenderManager rm, ViewPort vp)`.
  137. Usage example:
  138. . Create a custom control interface.
  139. +
  140. [source,java]
  141. ----
  142. public interface MyControlInterface extends Control {   
  143. public void setSomething(int x); // optionally, add custom methods
  144. }
  145. ----
  146. . Create custom Controls implementing your Control interface.
  147. +
  148. [source,java]
  149. ----
  150. public class MyControl extends MyCustomClass implements MyControlInterface {
  151.     protected Spatial spatial;
  152.     protected boolean enabled = true;
  153.     public MyControl() { } // empty serialization constructor
  154.    
  155. public MyControl(int x) { // custom constructor       
  156. super(x);   
  157. }
  158.     @Override   
  159. public void update(float tpf) {       
  160. if (enabled && spatial != null) {           
  161. // Write custom code to control the spatial here!       
  162. }   
  163. }       
  164. @Override   
  165. public void render(RenderManager rm, ViewPort vp) {       
  166. // optional for advanced users, e.g. to display a debug shape   
  167. }       
  168. @Override   
  169. public Control cloneForSpatial(Spatial spatial) {       
  170. MyControl control = new MyControl();       
  171. // set custom properties       
  172. control.setSpatial(spatial);       
  173. control.setEnabled(isEnabled());        
  174. // set some more properties here...       
  175. return control;   
  176. }       
  177. @Override   
  178. public void setEnabled(boolean enabled) {       
  179. this.enabled = enabled;   
  180. }       
  181. @Override   
  182. public boolean isEnabled() {       
  183. return enabled;   
  184. }       
  185. @Override   
  186. public void setSomething(int z) {       
  187. // You can add custom methods ...   
  188. }       
  189. @Override   
  190. public void write(JmeExporter ex) throws IOException {       
  191. super.write(ex);       
  192. OutputCapsule oc = ex.getCapsule(this);       
  193. oc.write(enabled, "enabled", true);       
  194. oc.write(spatial, "spatial", null);       
  195. // write custom variables ....   
  196. }   
  197. @Override   
  198. public void read(JmeImporter im) throws IOException {       
  199. super.read(im);       
  200. InputCapsule ic = im.getCapsule(this);       
  201. enabled = ic.readBoolean("enabled", true);       
  202. spatial = (Spatial) ic.readSavable("spatial", null);       
  203. // read custom variables ....   
  204. }
  205. }
  206. ----
  207. == Best Practices
  208. Use the getControl() accessor to get Control objects from Spatials. No need to pass around lots of object references. Here's an example from the link:http://code.google.com/p/monkeyzone/[MonkeyZone] code:
  209. [source,java]
  210. ----
  211. public class CharacterAnimControl implements Control { 
  212. ... 
  213. public void setSpatial(Spatial spatial) {   
  214. ...   
  215. animControl      = spatial.getControl(AnimControl.class);   
  216. characterControl = spatial.getControl(CharacterControl.class);   
  217. ... 
  218. }
  219. }
  220. ----
  221. You can create custom Control interfaces so a set of different Controls provide the same methods and can be accessed with the interface class type.
  222. [source,java]
  223. ----
  224. public interface ManualControl extends Control {   
  225. public void steerX(float value);   
  226. public void steerY(float value);   
  227. public void moveX(float value);   
  228. public void moveY(float value);   
  229. public void moveZ(float value);  
  230. ...
  231. }
  232. ----
  233. Then you create custom sub-Controls and implement the methods accordingly to the context:
  234. [source,java]
  235. ----
  236. public class ManualVehicleControl   extends ManualControl {...}
  237. ----
  238. and
  239. [source,java]
  240. ----
  241. public class ManualCharacterControl extends ManualControl {...}
  242. ----
  243. Then add the appropriate controls to spatials:
  244. [source,java]
  245. ----
  246. characterSpatial.addControl(new ManualCharacterControl());
  247. ...
  248. vehicleSpatial.addControl(new ManualVehicleControl());
  249. ...
  250. ----
  251. [TIP]
  252. ====
  253. Use the getControl() method on a Spatial to get a specific Control object, and activate its behaviour!
  254. [source,java]
  255. ----
  256. ManualControl c = mySpatial.getControl(ManualControl.class);
  257. c.steerX(steerX);
  258. ----
  259. ====