= Walking Character :revnumber: 2.1 :revdate: 2020/07/24 :keywords: documentation, physics, input, animation, character, NPC, collision In the xref:tutorials:beginner/hello_collision.adoc[Hello Collision] tutorial and the link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-examples/src/main/java/jme3test/bullet/TestQ3.java[TestQ3.java] code sample you have seen how to create collidable landscapes and walk around in a first-person perspective. The first-person camera is enclosed by a collision shape and is steered by the BetterCharacterControl. Other games however require a third-person perspective of the character: In these cases you use a CharacterControl on a Spatial. This example also shows how to set up custom navigation controls, so you can press WASD to make the third-person character walk; and how to implement dragging the mouse to rotate. == Sample Code Several related code samples can be found here: * link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-examples/src/main/java/jme3test/bullet/TestPhysicsCharacter.java[TestPhysicsCharacter.java] (third-person view) * link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-examples/src/main/java/jme3test/bullet/TestWalkingChar.java[TestWalkingChar.java] (third-person view) ** Uses also link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-examples/src/main/java/jme3test/bullet/BombControl.java[BombControl.java] * link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-examples/src/main/java/jme3test/bullet/TestQ3.java[TestQ3.java] (first-person view) * link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-examples/src/main/java/jme3test/helloworld/HelloCollision.java[HelloCollision.java] (first-person view) The code in this tutorial is a combination of these samples. == BetterCharacterControl Motivation: When you load a character model, give it a RigidBodyControl, and use forces to push it around, you do not get the desired behaviour: RigidBodyControl'ed objects (such as cubes and spheres) roll or tip over when pushed by physical forces. This is not the behaviour that you expect of a walking character. JME3's BulletPhysics integration offers a BetterCharacterControl with a `setWalkDirection()` method. You use it to create simple characters that treat floors and walls as solid, and always stays locked upright while moving. To use the BetterCharacterControl, you may load your character like this: [source,java] ---- // Load any model Spatial playerSpatial = assetManager.loadModel("Models/Oto/Oto.mesh.xml"); player = (Node)playerSpatial; // You can set the model directly to the player. (We just wanted to explicitly show that it's a spatial.) Node playerNode = new Node(); // You can create a new node to wrap your player to adjust the location. (This allows you to solve issues with character sinking into floor, etc.) playerNode.attachChild(player); // add it to the wrapper player.move(0,3.5f,0); // adjust position to ensure collisions occur correctly. player.setLocalScale(0.5f); // optionally adjust scale of model // setup animation: control = player.getControl(AnimControl.class); control.addListener(this); channel = control.createChannel(); channel.setAnim("stand"); playerControl = new BetterCharacterControl(1.5f, 6f, 1f); // construct character. (If your character bounces, try increasing height and weight.) playerNode.addControl(playerControl); // attach to wrapper // set basic physical properties: playerControl.setJumpForce(new Vector3f(0,5f,0)); playerControl.warp(new Vector3f(0,10,10)); // warp character into landscape at particular location // add to physics state bulletAppState.getPhysicsSpace().add(playerControl); bulletAppState.getPhysicsSpace().addAll(playerNode); // You can change the gravity of individual physics objects after they are // added to the PhysicsSpace. playerControl.setGravity(new Vector3f(0,-1f,0)); rootNode.attachChild(playerNode); // add wrapper to root ---- This table doesn't contain all of the methods of the BetterCharacterControl class, just the commonly used ones. For a full list, see the link:{link-javadoc}/com/jme3/bullet/control/BetterCharacterControl.html[java doc]. [cols="2", options="header"] |=== a| BetterCharacterControl Method a| Property a| warp(new Vector3f(0,10,10) a| Move the character somewhere. Note the character also takes the location of any spatial its being attached to at the moment it is attached. a| jump() a| Makes the character jump with the set jump force. a| setJumpForce(new Vector3f(0,5f,0) a| Set the jump force as a Vector3f. The jump force is local to the characters coordinate system, which normally is always z-forward (in world coordinates, parent coordinates when set to applyLocalPhysics) a| isOnGround() a| Check if the character is on the ground. This is determined by a ray test in the center of the character and might return false even if the character is not falling yet. a| setDucked(true) a| Toggle character ducking. When ducked the characters capsule collision shape height will be multiplied by duckedFactor to make the capsule smaller. When unducking, the character will check with a ray test if it can in fact unduck and only do so when its possible. You can check the state of the unducking by checking isDucked(). a| setDuckedFactor(2.0f) a| The factor by which the height should be multiplied when ducking. a|setWalkDirection(new Vector3f(0f,0f,0.1f)) a|Sets the walk direction of the character. This parameter is frame rate independent and the character will move continuously in the direction given by the vector with the speed given by the vector length in m/s. a|setViewDirection(new Vector3f(0f,0f,0.1f)) a|Sets the view direction for the character. Note this only defines the rotation of the spatial in the local x/z plane of the character. a|resetForward(new Vector3f(0f,0f,0.1f)) a|Realign the local forward vector to given direction vector, if null is supplied Vector3f.UNIT_Z is used. Input vector has to be perpendicular to current gravity vector. This normally only needs to be called when the gravity direction changed continuously and the local forward vector is off due to drift. E.g. after walking around on a sphere "planet" for a while and then going back to a y-up coordinate system the local z-forward might not be 100% aligned with Z axis. a|setGravity(new Vector3f(0,-1f,0)) a|Set the gravity for this character. Note that this also realigns the local coordinate system of the character so that continuous changes in gravity direction are possible while maintaining a sensible control over the character. Only takes effect if the individual physics object has already been added to the PhysicsSpace, otherwise it adopts the PhysicsSpace gravity. a|setPhysicsDamping(0.9f) a|Sets how much the physics forces in the local x/z plane should be dampened. 0 = no dampening, 1 = no external force, default = 0.9 a|setHeightPercent(float percent) a|This actually sets a new collision shape to the character to change the height of the capsule. |=== == Character Control This code sample creates a simple upright Character using a CharacterControl: [source,java] ---- // Load any model Node myCharacter = (Node) assetManager.loadModel("Models/myCharacterModel.mesh.xml"); rootNode.attachChild(myCharacter); // Create a appropriate physical shape for it CapsuleCollisionShape capsuleShape = new CapsuleCollisionShape(1.5f, 6f, 1); CharacterControl myCharacter_phys = new CharacterControl(capsuleShape, 0.01f); // Attach physical properties to model and PhysicsSpace myCharacter.addControl(myCharacter_phys); bulletAppState.getPhysicsSpace().add(myCharacter_phys); ---- [IMPORTANT] ==== The BulletPhysics CharacterControl only collides with "`real`" PhysicsControls (RigidBody). It does not detect collisions with other CharacterControls! If you need additional collision checks, add GhostControls to your characters and create a custom xref:collision/physics_listeners.adoc[collision listener] to respond. ==== A CharacterControl is a special kinematic object with restricted movement. CharacterControls have a fixed "`upward`" axis, this means they do not topple over when walking over an obstacle (as opposed to RigidBodyControls), which simulates a being's ability to balance upright. A CharacterControl can jump and fall along its upward axis, and it can scale steps of a certain height/steepness. [cols="2", options="header"] |=== a| CharacterControl Method a| Property a| setUpAxis(1) a| Fixed upward axis. Values: 0 = X axis , 1 = Y axis , 2 = Z axis. + Default: 1, because for characters and vehicles, up is typically along the Y axis. a| setJumpSpeed(10f) a| Jump speed (movement along upward-axis) a| setFallSpeed(20f) a| Fall speed (movement opposite to upward-axis) a| setMaxSlope(1.5f) a| How steep the slopes and steps are that the character can climb without considering them an obstacle. Higher obstacles need to be jumped. Vertical height in world units. .3f) { if (!"stand".equals(animationChannel.getAnimationName())) { animationChannel.setAnim("stand"); } } else if (!"Walk".equals(animationChannel.getAnimationName())) { animationChannel.setAnim("Walk", 0.7f); } } walkDirection.multLocal(25f).multLocal(tpf);// The use of the first multLocal here is to control the rate of movement multiplier for character walk speed. The second one is to make sure the character walks the same speed no matter what the frame rate is. character.setWalkDirection(walkDirection); // THIS IS WHERE THE WALKING HAPPENS } ---- This method resets the walk animation. [source,java] ---- public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) { if (channel == attackChannel) channel.setAnim("stand"); } public void onAnimChange(AnimControl control, AnimChannel channel, String animName) { } ---- --- See also: * link:https://hub.jmonkeyengine.org/t/bettercharactercontrol-in-the-works/25242[https://hub.jmonkeyengine.org/t/bettercharactercontrol-in-the-works/25242]