This is an example from the Unity official website Walk script, after my simple finishing post here, write very good, well-organized, at a glance, run up very operation feel.
This script runs under the animator system, so you need to make some simple settings for the animator controller before writing this script:
1. Idle state (default) and run state (blend tree, mixed with walk and run)
2. Define a float type parameter, Idle->run (speed>0.1), Run->idle (speed<0.1)
3. Automatically match the speed as a transition animation parameter in the Run's Blend tree (method: Compute thresholds, select speed)
4. Add a Rigidbody and collider to the protagonist
5. Tick apply Root montion and use the pace of the model walk to calculate the walking distance
usingUnityengine;usingSystem.Collections; Public classTest:monobehaviour { PublicAnimator Anim; PublicRigidbody RB; Public floatturnsmoothing = 15f;//speed of the player's smooth steering Public floatSpeeddamptime =0.1f;//Speed Buffer Time voidfixedupdate () {floatH = Input.getaxis ("Horizontal"); floatv = Input.getaxis ("Vertical"); Movementmanagement (h, v); } voidMovementmanagement (floatHorizontal,floatvertical) { //if the horizontal or vertical button is pressed, which means the role is moving if(Horizontal! = 0f | | Vertical! =0f) {//set player rotation and set speed to 5.5rotating (horizontal, vertical); //function parameter Interpretation Anim. SetFloat (current speed, max speed, acceleration buffer time, incremental time)Anim. SetFloat (" Speed",5.5f, Speeddamptime, time.deltatime); } Else //otherwise set the role speed to 0Anim. SetFloat (" Speed",0); } voidRotating (floatHorizontal,floatvertical) { //to create a vector for a character's target directionVector3 targetdirection =NewVector3 (horizontal, 0f, vertical); //Create a target rotation value//The corresponding parameters are 1. Four yuan to see the target 2. Need to rotate along the axisquaternion targetrotation =quaternion.lookrotation (targetdirection, vector3.up); //creates a new rotation value and smoothly goes to the target rotation value based on the steering speedquaternion newrotation = Quaternion.lerp (rb.rotation, targetrotation, turnsmoothing *time.deltatime); //Update rigid body rotation value to new rotation valueRB. Moverotation (newrotation); }}
Ps:
The code that handles the physical effects needs to be written in the fixedupdate function;
The three elements of the complete walk are animation, rotation, movement, the example of the animation and rotation are written in 2 methods, mobile use of the pace of the model automatically calculated;
The moving of the role of Unity3d--the keyboard moving from the view angle to the outside chapter