User Tools

Site Tools


dragengine:modules:dragonscript:locomotion

Locomotion

Locomotion defines the movement, looking, turnging and stance states of actors. The DragonScript module provides basic locomotion implementation using the locomotion class. Three kinds of locomotion types are well supported and can be extended according to needs. For performance reasons the locomotion class is implemented as native class. It is possible to extend the behavior but requires extending the class in a specific way to work. Whenever the player or an AI routine creates input new goals are set in the locomotion. The locomotion class then updates the actual values. Internal this uses smooth values to smoothly apply changes over time. The resulting parameters can then be used to update colliders for collision testing and animator instances for calculating animation states.

Parameters

The locomotion class uses various parameters and switches to provide the different kinds of locomotion behaviors. Input parameters are described in this article as Parameter-Sets. A Parameter-Set composes of different class members related to the same parameter.

Class-MemberDescription
ValueThe current value of the parameter. This is the output of the locomotion.
GoalThe desired value of the parameter. This is set by the script user according to input from the player or AI. Smoothing is used to adjust the current value over time to arrive at the goal.
Adjust timeTime after which the current value approached the goal value. Due to goal values keeping on changing this is only an approximation and should is a best effort value. Compare the current value against the goal value to figure out when the value is close enough to the desired value. Adjust time can be set to 0 in which case the locomotion class sets the current value to the goal value without smoothing.
Lower limitLower limit to clamp current value to. The goal value is allowed to go below the lower limit to avoid clipping problems. Some parameter sets do not have a lower limit.
Upper limitUpper limit to clamp current value to. The goal value is allowed to go above the upper limit to avoid clipping problems. Some parameter sets do not have an upper limit.

The following Input Parameter Sets are used.

Parameter-SetTypeDescription
Look up-downfloatControls actor looking up and down. Positive values represent looking up and negative values looking down. The default adjust time is 0. This value is typically set from user input for example moving the mouse or gamepad Y Axis. For AI actors this is usually calculated from a look-at point relative to the actor coordinate system.
Look left-rightfloatControls actor looking left and right. Positive values represent looking left and negative values looking right. The default adjust time is 0. This value is typically set from user input for example moving the mouse or gamepad X axis. For AI actors this is usually calculated from a look-at point relative to the actor coordinate system.
Analog moving directionfloatControls the direction the actor is moving to. This value is typically set from user input for example pressing direction buttons or using gamepad axes. For AI actors this is usually calculated from a target position. This value is in world space not relative to the actor. The default adjust time is 0.5s to smooth speed and direction changes.
Analog moving speedfloatControls the speed the actor is moving with as meters per second. This parameter does not support smoothing.
Turn left-rightfloatControls actor turning left and right. Positive values represent turning left and negative values turning right. This value is typically set from user input for example pressing direction buttons or using gamepad axes. For AI actors this is usually calculated from a target orientation. This value is the amount of degrees to rotate in the next frame update. This input parameter is not smoothed since it is not used directly as output parameter. For player actors turning is usually only required for doing vehicle like locomotion. For natural and FPS type locomotion this parameter is not required since the locomotion class can turn the actor using the Look left-right parameter.
StancefloatControls the actor stance for example in upright position or crouched. The actual meaning of this value is left for the user to define as long as smoothing is reasonable. This value is typically set from user input for example pressing buttons converting to appropriate goal value.
Tilt left-rightfloatControls actors standing on tilted ground. Positive values represent ground tilted downwards to the left side and negative to the right side. This value can be calculated by the script user but it is more efficient and easier to make the locomotion calculate tilt values. See the section below about tilting.
Tilt up-downfloatControls actors standing on tilted ground. Positive values represent ground tilted downwards to the front and negative to the back. This value can be calculated by the script user but it is more efficient and easier to make the locomotion calculate tilt values. See the section below about tilting.

The following Output Parameters are used.

ParameterValueDescription
Look up-downfloatHead up-down orientation relative to actor coordinate system. The current value of the Look up-down input parameter set after smoothing.
Look left-rightfloatHead left-right orientation relative to Orientation. The current value of the Look left-right input parameter set after smoothing.
OrientationfloatOrientation of actor in world space. This value is normalized to the range from -180 degrees to 180 degrees. Rotation is counter-clock-wise. This output value is smoothed after applying all rotation changes. It is possible to smooth input Look left-right and output Orientation but results are better if only one parameter is smoothed. The value is also provided as Quaternion for convenience.
Turning speedfloatTurning speed of actor in degrees per second. This value is also provided as angular velocity (Vector) for convenience.
Linear velocityVectorLinear velocity of actor in meters per second. This output value is smoothed after applying all movement changes and is used as base for all movement output parameters. It is possible to smooth input Analog moving direction/speed and output Linear velocity but results are better if only one parameter is smoothed.
Moving orientationfloatOrientation the actor is moving along in world space. Derived from the Linear velocity parameter. This value is normalized to the range from -180 degrees to 180 degrees. Rotation is counter-clock-wise. Near 0 movement speed the value of moving orientation becomes undefined. For this reason near 0 movement speed the moving orientation is not updated. The actor thus sticks to the last well defined moving orientation while stopping moving.
Moving speedfloatMoving speed of actor in meters per second. Derived from the Linear velocity parameter.
Moving directionfloatMoving orientation relative to actor instead of world. Useful for FPS type locomotion to choose the right leg animation. This value is normalized to the range from -180 degrees to 180 degrees. Value 0 represents moving straight forward and +/-180.0 moving straight backward. Positive values represent moving to the left side and negative moving to the right side.
StanceflotStance of active. The current value of the Stance input parameter set after smoothing.
Turn in-placefloatActor turning in-place. This is a special value to help properly animate actors turning in place. For moving actors this is not required since the Turning speed parameter is enough. For resting actors though this is usually not enough if a good animation is desired.
Tilt left-rightfloatActor tilt on ground. The current value of the Tilt left-right input parameter set after smoothing.
Tilt up-downfloatActor tilt on ground. The current value of the Tilt up-down input parameter set after smoothing.
Tilt offsetfloatUp-down offset of actor due to tilting. This offset is required if inverse kinematics is used for legs to avoid broken results.

Different locomotion calculation parts can be individually disabled using Switches to obtain one of the major locomotion types as well as dealing with different states actors can be in. Using the flexible parameters the locomotion behavior can be quickly changed for actors without risking snappy motions. For example an actor using natural locomotion taking a seat is switched over to a vehicle type locomotion since it can no turn any more. The following Switches are used:

SwitchDescription
Can turnDisabled turning calculations. If disabled the Orientation output parameter value is frozen and all kinds of orientation changes are prohibited. Useful for actors requiring to not change their orientation no matter what. Disabling this switch overrides enabling Turn adjust look left-right and Can turn in-place.
Can turn in-placeIf enabled and Look left-right input parameter changes beyond a threshold angle the actor is automatically turned to avoid the input value to be clamped. Basically this switch enforces left-right turning by players to be fully applied even if the actor is forcefully adjusted. This makes turning smooth in the eyes of the player. Disable this switch if the player left-right looking has to be clamped for example if seated on a chair where the actor is not able to rotate.
Turn adjust look left-rightIf enabled the rotation applied to the Orientation output parameter is subtracted from the Look left-right input parameter. This has the effect that while rotating the actor keeps looking into the same direction. If disabled the actor turns without turning his head.
Can tiltIf enabled tilt calculations are applied. If disabled tilt values are pulled towards neutral values.

Natural Locomotion

Natural locomotion parameter relationships

Natural locomotion parameter relationships.

Natural locomotion provides a smooth moving actor locomotion behavior that mimicks a natural locomotion pattern. This is the most complex calculation method but yields a result which is more natural than the other types. With natural locomotion the body orientation is the major orientation. The major orientation is the orientation lining up with the component, collider and game element orientation. All other orientations are relative to this major orientation. The looking left/right is applied ontop of the body orientation resulting in the camera direction. This is the direction a first person camera faces. This mimicks real world locomotion where somebody looks first into the direction he is going to turn before actually gently applying the turning. As a result actors move in a slight arc around corners which is not only more natural it also avoid actors getting stuck at corners. Furthermore the moving left/right defines the movement direction relative to the body orientation. This results in the moving direction which is the direction in which the actor actually moves during the next physics simulation. Moving covers inputs like strafing or moving forward/backward. It is does measured as angle relative to the body orientation in which the actor wants to move. The locomotion class adjusts the body orientation over time to match the moving direction. This also reflects a more natural locomotion since a person moving to the left or right turns the body into the moving direction to some degree. Of course this change is also applied to the look left/right direction but in reverse. So moving to the right the body is turned to the right while looking is towards the left to compensate. The locomotion class takes care of these details. All relative input values can be also analog values which is useful for AI scripts or player doing mouse input. The image below shows the relationship between the major parameters.

To use natural locomotion use the following Switches:

SwitchValue
Can turntrue
Turn adjust look left-righttrue
Can turn in-placetrue

Drive Input Parameter Sets like this:

Parameter-SetGoal value
Analog moving directionCalculate movingDirection depending on pressed buttons (forward, backward, strafe-left, strafe-right). Parameter value is then movingDirection + Look left-right.Value. Without pressing buttons the actor moves into the direction he is looking. movingDirection provides strafing behavior.
Turn left-rightTurning is used here to turn the body into the direction the actor is moving. Set value to Look left-right.Goal + DEMath.normalize(movingDirection, -91, 91). The normalize is used to switch the body direction while moving backward since otherwise it would be wrong. Optionally you can set the value to 0 if the player presses no movement keys to stop the body moving.

Natural locomotion is a good choice for most situations. Actors using natural locomotion move in the direction their body is facing and strafing behavior does not produce broken hips all the time. Another advantage of using natural locomotion is that only a single animation for moving forward and backward is required paired with looking left-right animator rules.

FPS Locomotion

FPS locomotion parameter relationships

FPS locomotion parameter relationships.

FPS locomotion is best known from FPS games as the name implies. In contrary to natural locomotion the camera direction and body orientation are coupled. The actor component is oriented to look into the same direction the camera is facing. In the case of natural locomotion the body orientation is the major oriented while in the case of FPS locomotion the camera direction is the major orientation. This is a typical coupling in FPS games and allows to animate upper and lower body individually (with the typical broken hip problem). The moving direction is now relative to the camera direction using looking left/right and moving left/right. The image below shows the relationship in the FPS locomotion case.

To use natural locomotion use the following Switches:

SwitchValue
Can turntrue
Turn adjust look left-righttrue
Can turn in-placetrue

Drive Input Parameter Sets like this:

Parameter-SetGoal value
Analog moving directionCalculate movingDirection depending on pressed buttons (forward, backward, strafe-left, strafe-right). Parameter value is then movingDirection + Look left-right.Value. Without pressing buttons the actor moves into the direction he is looking. movingDirection provides strafing behavior.
Turn left-rightTurning is used here to turn the body into the direction the actor is moving. Set value to Look left-right.Goal. Optionally you can set the value to 0 if the player presses no movement keys to stop the body moving.

FPS locomotion is somewhat simpler to understand and is somewhat cheaper to calculate. There are two ways to handle the animation. The first solution is to use the same setup as in the natural locomotion case. Most of the time though an 8-way animation setup is used. In this case 8 animations of walking/running are created each representing the same movement but in a different direction relative to the camera direction. 8 animations are typically chosen this this way each animation is 45 degrees rotate compared to the next animation working well with digital input from 4 direction keys (north, north-west, west, south-west, south, south-east, east, norh-east). This setup requires more animation work to be done but has the advantage that all kinds of moving directions can be blended together with good quality. As a side note this setup could be also used for the naturla locomotion case but it is a bit delicate to get working in a pleasant way. This setup can be easily build using the group animator rule using the select mode. There the 8 animations can be added as 8 rules in the group and selecting being driven by the moving orientation.

Vehicle Locomotion

FPS locomotion parameter relationships

FPS locomotion parameter relationships.

Vehicle locomotion matches the typical tank like controls. Actors can only move into the direction their body is oriented. The major direction is thus the body orientation similar to natural locomotion. The body orientation though never changes except using turning left/right. The looking left/right is only used to point the camera into a direction other than the moving direction. With the tank example this allows to point and fire weapons into a different direction than the vehicle is moving. The image below shows the relationships.

To use natural locomotion use the following Switches:

SwitchValue
Can turntrue
Turn adjust look left-rightfalse
Can turn in-placefalse

Drive Input Parameter Sets like this:

Parameter-SetGoal value
Analog moving direction0 if moving forward, 180 if moving backward.
Turn left-rightCurrentValue +/- turnSpeed * elapsedFrameTime. Turning speed is in degrees per second. Use positive value to turn left and negative to turn right.

Vehicle locomotion is the simplest locomotion type of the three and the cheapest. Disabling the turning adjustments and in-place turning is important to avoid the vehicle suddenly turning when the looking around approaches the border.

Animator and collider control

Locomotion allows to set an animator instance and mapping controllers. If set the locomotion updates the animator instance controllers with the appropriate locomotion values automatically upon updating. This is a convenience behavior of the locomotion class to improve performance since all this work is repetitive and can be done faster in C++ than inside scripts. The locomotion class documentation contains a list of supported controller mapping constants. The example below shows a typical setup.

// animator instance to manipulate
locomotion.setAnimatorInstance( actorAnimatorInstance )

// controller 0 will be incremented by the elapsed time
locomotion.addControllerMaping( 0, Locomotion.ATTR_ELAPSED_TIME )

// set controller 1 to looking left/right relative to body orientation
locomotion.addControllerMaping( 1, Locomotion.ATTR_LOOK_LEFT_RIGHT )

// upon calling locomotion.updateLocomotion() these controllers will be updated according
// to the mapping constant. not set controllers are left unchanged

The table below lists the available controllers and what they are best used for:

AttributeDescription
Elapsed timeIncrements controller using elapsed frame time. Use for all playback driven animations permanently playing.
Look up-downValue of Look up-down output parameter. Use for actor looking up-down without moving body.
Look left-rightValue of Look left-right output parameter. Use for actor looking left-right without moving body. With vehicles this could be used for example for rotating turrets.
Moving speedValue of Moving speed output parameter. Use to blend between different movement animations like walking and running. The value can not be used for blending between moving forward and backward since moving speed is always positive.
Moving directionValue of Moving direction output parameter. Use for actors using FPS type locomotion to blend between 4-way or 8-way movement animations. The most simple solution is using a Group Animator Rule set to the Select type and placing 8 Animation Rule inside one for each direction. The first animation has to be backwards with the following animations rotating clock-wise. The group then properly blends between them with no extra work.
Relative moving speedValue of Moving speed output parameter using the value of Moving direction to produce negative values if moving backwards. Use for actors using natural type locomotion to blend between different movement animations including forward/backward variations. Building such an animator is more complex but yields good results.
Turning speedValue of Turning speed output parameter. Use to blend with animations of the actor turning left or right. Turning speed is positive for turning left and negative for turning right.
StanceValue of Stance output parameter. Use to blend between different stances of an actor. The meaning of the value is up to the script user. Only requirement is that values are between 0 and 1.
DisplacementValue of Moving speed output parameter multiplied by the elapsed time. Use for movement animations to match the playback to the actual distance travelled. For this to work set the animator controller upper limit to the two times the stride length of the actor (if you use an animation with one walk cycle). The actor will then always move with the correct speed avoid feet sliding. This attribute works best for vehicle type locomotion for example tanks.
Time turn in-placeValue of Turn in-place output parameter. Use for animation of actor turning without moving. The attribute starts playing back similar to Elapsed time if the actor starts turning in place and stops once finished.
Tilt offsetValue of Tilt offset output parameter. Use to offset actor root bone downwards due to tilting. The value is the required offset in meters. Using this attribute moves actors on titled surfaces into a favorable position for inverse kinematic rules.
Tilt up-downValue of Tilt up-down output parameter. Use to blend with animation of actor in tilted position. Value is degrees of tilting. Positive values represent ground falling down to the left and negative falling down to the right.
Tilt left-rightValue of Tilt left-right output parameter. Use to blend with animation of actor in tilted position. Value is degrees of tilting. Positive values represent ground falling down to the front and negative falling down to the back.

Body tilting

Weighted body tile testing locations

Weighted body tile testing locations.

Body tilting provides support to adjust animations of actors to better fit them to uneven ground. Body tilting require collider collision tests to determine the distances required to calculate proper tilting. The testing is done after the physics simulation step. For this reason locomotion calculation has to be split into a part before physics simulation (during Element.think) and a part after physics simulation (during Element.postThink). Locomotion can be set to do no body tilt calculation, single or weighted. In single mode one collision test is used usually straight under the actor. The hit normal on the ground is used to calculate the tilting on a virtual plane located under the actor with the hit normal matching the plane normal. This is fast and for many situations reasonable solution. In weighted mode 4 collision tests are used each of them located near feet like if the actor is quadripedal (if not really the case). The image below shows the layout.

The results are weighted to get a best matching virtual ground plane. This mode is most expensive but the results are more stable and of higher quality. Once done the tilt result can be applied to animator instance controlls as any other locomotion state.

func void init()
  // set up locomotion body tilt for an actor using the weighted method
  locomotion.setTiltMode( Locomotion.TILT_WEIGHTED )
  
  // create collision filter shared by all tests
  var LayerMask category = LayerMask.new()
  category.setBit( GameState.CL_AI )      // we are an collider for doing actor ai
  
  var LayerMask filter = LayerMask.new()
  filter.setBit( GameState.CL_GEOMETRY )  // we can hit geometry like the ground
  filter.setBit( GameState.CL_AI )        // we can hit other actor ai colliders
  
  var CollisionFilter collisionFilter = CollisionFilter.new( category, filter )
  
  // set collision test. the test points are located above the ground since otherwise tilting up can not
  // be detected. as a rule of thumb the test distance should be two times the start height. for each
  // test a ray test is used. this is the fastest solution and works well for most situations.
  var float offset = 0.5                  // height above ground to start testing
  var Vector testDistance = Vector.new( 0.0, -offset * 2.0, 0.0 )          // distance to test downwards
  
  locomotion.setCCTTiltFrontLeft( ColliderCollisionTest.new( touchSensor, touchSensorShape, \
    collisionFilter, Vector.new( -0.2, offset, 0.2 ), testDistance ) )
  locomotion.setCCTTiltFrontRight( ColliderCollisionTest.new( touchSensor, touchSensorShape, \
    collisionFilter, Vector.new( 0.2, offset, 0.2 ), testDistance ) )
  locomotion.setCCTTiltBackLeft( ColliderCollisionTest.new( touchSensor, touchSensorShape, \
    collisionFilter, Vector.new( -0.2, offset, -0.2 ), testDistance ) )
  locomotion.setCCTTiltBackRight( ColliderCollisionTest.new( touchSensor, touchSensorShape, \
    collisionFilter, Vector.new( 0.2, offset, -0.2 ), testDistance ) )
  
  // add mappings so our animator uses the calculated values
  locomotion.addControllerMaping( controllerTiltOffset, Locomotion.ATTR_TILT_OFFSET )
  locomotion.addControllerMaping( controllerTiltUpDown, Locomotion.ATTR_TILT_UP_DOWN )
  locomotion.addControllerMaping( controllerTiltLeftRight, Locomotion.ATTR_TILT_RIGHT_LEFT )
end

// tilt is enabled so during Element.postThink the tilt is updated automatically and the result
// applied to animator instance controllers
func void postThink( float elapsedFrameTime )
  locomotion.updatePostLocomotion( elapsedFrameTime )
end

State control and frame update

To update the locomomotion multiple calls are used. After the player has provided input the updateLooking() method can be used to smooth the input and to update the goal values used by the locomotion calculation step. Once the input is updated the locomotion can be calculated using updateLocomotion() method. This calculates all the needed locomotion states using native code. This call is used during Element.think(). After the physics simulation is done the updatePostLocomotion method can be called to calculate body tilting and potential other calculations requiring physics test results. Afterward the animation instance has to be updated if not assigned to be done by the locomotion instance directly.

If you want to enhance the locomotion class you have to be careful about the calling structure. The native classes methods call themselves internally for performance reasons. The entire late binding is skipped. Overwriting the update calls has no effect in this case. To partially change behavior you have to implement the updateLocomotion() and updatePostLocomotion() calls yourself and call the native methods from the script. This allows to inject your changes in the right place. This all works since it is no problem to call a method from script if it is a native class but the native class.

Player Input Tracker

To help with managing the player input for use with locomotions the DragonScript module provides a helper class PlayerInputTracker. This class is not mandatory but reduces implementation needs. The player input tracks what inputs the player has provided so far and calculates the goal locomotion changes my smoothing the changes over time using smooth values. Tracks digital input (pressing buttons like forward or strafing) as well as analog input (mouse, joystick axes). Call updateLocomotion() to smooth the input values and setting the appropriate goal values in a locomotion instance.

The Player Input Tracker supports all three mentioned locomotion types and has similar Switches like the locomotion class to disable individual calculations. The most simple use is like this:

// create an input tracker and set parameters
func void init()
  tracker.setSpeedLookLeftRight( 45.0 ) // degrees per second
  tracker.setSpeedLookUpDown( 45.0 ) // degrees per second
  tracker.setSpeedTurnLeftRight( 30.0 ) // degrees per second. for vehicle type locomotion
  tracker.setCanTurn( true ) // player turning commands are used
  tracker.setCanMove( true ) // player movement commands are used
  tracker.setCanChangeStance( true ) // player stance change commands are used
  tracker.setSpeedWalk( 3.0 ) // meters per second. you can set backward speed individually
  tracker.setSpeedRun( 8.0 ) // meters per second. you can set backward speed individually
end

// in reaction to player input commands alter state
func void playerPressForward()
  tracker.setMoveForward( true ) // button press (true), button release (false).
end

func void playerMoveMouse( Point mouseMovement )
  // mouse movement during this frame update for natural and fps locomotion
  tracker.setAnalogLookLeftRight( mouseMovement.getX() )
  tracker.setAnalogLookUpDown mouseMovement.getY() )
end

func void playerPressTurnVehicle()
  tracker.setTurnLeft( true ) // turning for vehicle type locomotion
end

// then during each Element.think() call let the tracker update the locomotion
func void think( float elapsedFrameTime )
  tracker.updateLocomotion( locomotion, elapsedFrameTime )
end

You could leave a comment if you were logged in.
dragengine/modules/dragonscript/locomotion.txt · Last modified: 2017/02/22 16:34 by dragonlord