custom_controls.adoc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. = Custom Controls
  2. :author:
  3. :revnumber:
  4. :revdate: 2016/03/17 20:48
  5. :relfileprefix: ../../
  6. :imagesdir: ../..
  7. :stylesheet: twemoji-awesome.css
  8. ifdef::env-github,env-browser[:outfilesuffix: .adoc]
  9. 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.
  10. To control global game behaviour see <<jme3/advanced/application_states#,Application States>> – you often use AppStates and Control together.
  11. * link:http://www.youtube.com/watch?v=MNDiZ9YHIpM[Quick video introduction to Custom Controls]
  12. To control the behaviour of spatials:
  13. . 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.
  14. +
  15. For example, one NPC can be controlled by a PhysicsControl instance and an AIControl instance.
  16. . Define the custom control and implement its behaviour in the Control's update method:
  17. ** You can pass arguments into your custom control.
  18. ** In the control class, the object `spatial` gives you access to the spatial and subspatials that the control is attached to.
  19. ** Here you modify the `spatial's` transformation (move, scale, rotate), play animations, check its environement, define how it acts and reacts.
  20. . 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.
  21. [source,java]
  22. ----
  23. spatial.addControl(myControl);
  24. ----
  25. 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.
  26. == Usage
  27. Use <<jme3/advanced/custom_controls#,Controls>> to implement the _behaviour of types of game entities_.
  28. * Use Controls to add a type of behaviour (that is, methods and fields) to individual Spatials.
  29. * Each Control has its own `update()` loop that hooks into `simpleUpdate()`. Use Controls to move blocks of code out of the `simpleUpdate()` loop.
  30. * One Spatial can be influenced by several Controls. (Very powerful and modular!)
  31. * Each Spatial needs its own instance of the Control.
  32. * A Control only has access to and control over the Spatial it is attached to.
  33. * Controls can be saved as .j3o file together with a Spatial.
  34. Examples: You can write
  35. * 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.
  36. * A PlayerNavControl that is steered by user-configurable keyboard and mouse input.
  37. * A generic animation control that acts as a common interface that triggers animations (walk, stand, attack, defend) for various entities.
  38. * A DefensiveBehaviourControl that remote-controls NPC behaviour in fight situations.
  39. * An IdleBehaviourControl that remote-controls NPC behaviour in neutral situations.
  40. * A DestructionControl that automatically replaces a structure with an appropriate piece of debris after collision with a projectile…
  41. The possibilities are endless. emoji:smile[]
  42. == Example Code
  43. 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.
  44. Existing examples in the code base include:
  45. * 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.
  46. * 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.
  47. * 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.
  48. * 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.
  49. == AbstractControl Class
  50. [TIP]
  51. ====
  52. The most common way to create a Control is to create a class that extends AbstractControl.
  53. ====
  54. The AbstractControl can be found under `com.jme3.scene.control.AbstractControl`. This is a default abstract class that implements the Control interface.
  55. * You have access to a boolean `isEnabled()`.
  56. * You have access to the Spatial object `spatial`.
  57. * You override the `controlUpdate()` method to implement the Spatial's behaviour.
  58. * 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.
  59. +
  60. For example, you disable your IdleBehaviourControl when you enable your DefensiveBehaviourControl in a spatial.
  61. Usage: Your custom subclass implements the three methods `controlUpdate()`, `controlRender()`, `setSpatial()`, and `cloneForSpatial()` as shown here:
  62. [source,java]
  63. ----
  64. public class MyControl extends AbstractControl implements Savable, Cloneable { 
  65. private int index; // can have custom fields -- example    
  66. public MyControl(){} // empty serialization constructor   
  67. /** Optional custom constructor with arguments that can init custom fields.   
  68. * Note: you cannot modify the spatial here yet!
  69. */ 
  70. public MyControl(int i){    
  71. // index=i; // example  
  72. }    
  73. /** This method is called when the control is added to the spatial,   
  74. * and when the control is removed from the spatial (setting a null value).   
  75. * It can be used for both initialization and cleanup.
  76. */     
  77. @Override 
  78. public void setSpatial(Spatial spatial) {   
  79. super.setSpatial(spatial);   
  80. /* Example:   
  81. if (spatial != null){       
  82. // initialize   
  83. }else{       
  84. // cleanup   
  85. }   
  86. */ 
  87. }
  88.  
  89. /** Implement your spatial's behaviour here.   
  90. * From here you can modify the scene graph and the spatial   
  91. * (transform them, get and set userdata, etc).   
  92. * This loop controls the spatial while the Control is enabled.
  93. */ 
  94. @Override 
  95. protected void controlUpdate(float tpf){   
  96. if(spatial != null) {     
  97. // spatial.rotate(tpf,tpf,tpf); // example behaviour   
  98. }   
  99. @Override 
  100. public Control cloneForSpatial(Spatial spatial){   
  101. final MyControl control = new MyControl();   
  102. /* Optional: use setters to copy userdata into the cloned control */   
  103. // control.setIndex(i); // example   
  104. control.setSpatial(spatial);   
  105. return control; 
  106. }   
  107. @Override 
  108. protected void controlRender(RenderManager rm, ViewPort vp){    
  109. /* Optional: rendering manipulation (for advanced users) */ 
  110. }   
  111. @Override 
  112. public void read(JmeImporter im) throws IOException {     
  113. super.read(im);     
  114. // im.getCapsule(this).read(...); 
  115. }   
  116. @Override 
  117. public void write(JmeExporter ex) throws IOException {     
  118. super.write(ex);     
  119. // ex.getCapsule(this).write(...); 
  120. }
  121. ----
  122. See also:
  123. * To learn more about `write()` and `read()`, see <<jme3/advanced/save_and_load#,Save and Load>>
  124. * To learn more about `setUserData()`, see <<jme3/advanced/spatial#,Spatial>>.
  125. == The Control Interface
  126. [TIP]
  127. ====
  128. 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.
  129. ====
  130. The Control interface can be found under `com.jme3.scene.control.Control`. It has the following method signatures:
  131. * `cloneForSpatial(Spatial)`: Clones the Control and attaches it to a clone of the given Spatial.
  132. +
  133. Implement this method to be able to <<jme3/advanced/save_and_load#,save() and load()>> Spatials carrying this Control.
  134. +
  135. 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.
  136. * `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.
  137. * 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)`.
  138. Usage example:
  139. . Create a custom control interface.
  140. +
  141. [source,java]
  142. ----
  143. public interface MyControlInterface extends Control {   
  144. public void setSomething(int x); // optionally, add custom methods
  145. }
  146. ----
  147. . Create custom Controls implementing your Control interface.
  148. +
  149. [source,java]
  150. ----
  151. public class MyControl extends MyCustomClass implements MyControlInterface {
  152.     protected Spatial spatial;
  153.     protected boolean enabled = true;
  154.     public MyControl() { } // empty serialization constructor
  155.    
  156. public MyControl(int x) { // custom constructor       
  157. super(x);   
  158. }
  159.     @Override   
  160. public void update(float tpf) {       
  161. if (enabled && spatial != null) {           
  162. // Write custom code to control the spatial here!       
  163. }   
  164. }       
  165. @Override   
  166. public void render(RenderManager rm, ViewPort vp) {       
  167. // optional for advanced users, e.g. to display a debug shape   
  168. }       
  169. @Override   
  170. public Control cloneForSpatial(Spatial spatial) {       
  171. MyControl control = new MyControl();       
  172. // set custom properties       
  173. control.setSpatial(spatial);       
  174. control.setEnabled(isEnabled());        
  175. // set some more properties here...       
  176. return control;   
  177. }       
  178. @Override   
  179. public void setEnabled(boolean enabled) {       
  180. this.enabled = enabled;   
  181. }       
  182. @Override   
  183. public boolean isEnabled() {       
  184. return enabled;   
  185. }       
  186. @Override   
  187. public void setSomething(int z) {       
  188. // You can add custom methods ...   
  189. }       
  190. @Override   
  191. public void write(JmeExporter ex) throws IOException {       
  192. super.write(ex);       
  193. OutputCapsule oc = ex.getCapsule(this);       
  194. oc.write(enabled, "enabled", true);       
  195. oc.write(spatial, "spatial", null);       
  196. // write custom variables ....   
  197. }   
  198. @Override   
  199. public void read(JmeImporter im) throws IOException {       
  200. super.read(im);       
  201. InputCapsule ic = im.getCapsule(this);       
  202. enabled = ic.readBoolean("enabled", true);       
  203. spatial = (Spatial) ic.readSavable("spatial", null);       
  204. // read custom variables ....   
  205. }
  206. }
  207. ----
  208. == Best Practices
  209. 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:https://code.google.com/archive/p/monkeyzone/[MonkeyZone] code:
  210. [source,java]
  211. ----
  212. public class CharacterAnimControl implements Control { 
  213. ... 
  214. public void setSpatial(Spatial spatial) {   
  215. ...   
  216. animControl      = spatial.getControl(AnimControl.class);   
  217. characterControl = spatial.getControl(CharacterControl.class);   
  218. ... 
  219. }
  220. }
  221. ----
  222. 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.
  223. [source,java]
  224. ----
  225. public interface ManualControl extends Control {   
  226. public void steerX(float value);   
  227. public void steerY(float value);   
  228. public void moveX(float value);   
  229. public void moveY(float value);   
  230. public void moveZ(float value);  
  231. ...
  232. }
  233. ----
  234. Then you create custom sub-Controls and implement the methods accordingly to the context:
  235. [source,java]
  236. ----
  237. public class ManualVehicleControl   extends ManualControl {...}
  238. ----
  239. and
  240. [source,java]
  241. ----
  242. public class ManualCharacterControl extends ManualControl {...}
  243. ----
  244. Then add the appropriate controls to spatials:
  245. [source,java]
  246. ----
  247. characterSpatial.addControl(new ManualCharacterControl());
  248. ...
  249. vehicleSpatial.addControl(new ManualVehicleControl());
  250. ...
  251. ----
  252. [TIP]
  253. ====
  254. Use the getControl() method on a Spatial to get a specific Control object, and activate its behaviour!
  255. [source,java]
  256. ----
  257. ManualControl c = mySpatial.getControl(ManualControl.class);
  258. c.steerX(steerX);
  259. ----
  260. ====