Create a character--03 state machine

Source: Internet
Author: User

Study Notes for beginners, please correct me if you have any mistakes. The number is also please point out, thank you.

State machines are primarily used for state management and state switching, such as running, jumping, and resting, all in a separate state, each with corresponding animations

Idle: Resting state

Run: Running state

Jump: Jumping State

Animator

Controller adds animator controller and re-name to Playercontroller

Click on the navigation menu bar Window Animator Navigation, open animator View

The upper left corner shows the selected base layer, which is currently editing the base Layer animation layer, we can also click the "+" button to create a new animation layer, an animation layer corresponding to a state machine, in general, different animation layer control different parts of the body

Each rectangular pattern in the diagram is a state, where entry is the initial state

Create a running state: Right-click in the editing area, "create", Empty

Select the first line of state we renamed run to move the animation file to the motion column, so we've built a complete state with animation

Run the scene, in scene view, see the character moving forward in the scene, but the character will be out of the wall, we still need to do 3 things:

1 Increasing the collision body

2 Adding a camera

3 Adding control functions

Adding a collision body

The Character controller is a class that inherits from the Collier,

Click the Add Component button at the bottom of the inspector, enter "Character controller" in the search bar and add and align the capsule that the Character Controller is staring at with the human model

Add camera

Create a camera and add a script named Thirdpersoncan

usingUnityengine;usingSystem.Collections; Public classthirdpersoncam:monobehaviour{//the object that the camera follows     PublicTransform Follow; //distance between the camera and the object in the horizontal direction     Public floatDistanceaway; //distance between the camera and the object in the vertical direction     Public floatDistanceup; //Transition Speed     Public floatSmooth; //target speed of the camera    PrivateVector3 targetposition; //perform camera operations in lateupdate to ensure that after the object's operation is complete    voidlateupdate () {//Calculate target LocationTargetposition = follow.position + vector3.up * Distanceup-follow.forward *Distanceaway; //interpolation calculation of the current positionTransform.position = Vector3.lerp (transform.position, targetposition, Time.deltatime *smooth); //make the camera observe objectstransform.    LookAt (follow); }}

Set the parameters as follows:

Follow: Set as player game object

Distance away: Set to 5

Distance up: Set to 2

Smooth: Set to 3

Motion Blending and control

Action blending is an important function in animation system.

For example: The character has the movement to move forward and to the left, the combination of the two is to the left to run the action

1 Action Mix

Back to Animator View

Create a float parameter named direction (used when setting the Blendtree mixed tree)

Click on the Parameters tab in the upper left corner of the animator, enter the animator parameter table view and click "+" "Float" button to create the parameter and name "Direction"

The float parameter "speed" is created in the same way, and the parameters are then used when switching between the idle and run states.

Finally, a bool parameter jump is created, which is used when switching between the run and jump states.

Create a direction parameter, create a blend tree,blend Tree is a blend of different animations

Select the run state, right-click the "Create New blendtree in State" button and double-click the Run status to enter Blendtree

Click the "+" "Add motion Field" button to add an action and assign the animation file to the Diagram Motion column and continue adding the run and run right actions

The parameter parameter column selects the previously created direction parameter from the Triangle drop-down menu on the right, which determines how the action is mixed, which can be understood as whether the character runs left or right.

Click "0" below the waveform. and enter-1.

The first triangle on the left side of the waveform represents runleft, the middle type represents run, the waveform on the right represents Runright, and the rarameter direction controls the

When 1, Runleft left to run the painting

When it is 0, run forward.

When 1 o'clock is the right run

When the value is between, for example 0.5 is a mix of forward and right running, that is, right ahead of the run

2 Motion Control

The input Control section, we mainly use Input.getaxis () and Animator.setfloat () these two excuses

Input.getaxis (): Returns axis, which is the value of the control axis,

You can also enter the input Settings screen by clicking on the Navigation menu bar, Edit Project Setting input menu, where we can define both the name and parameters of the horizontal and vertical axes, as well as the names and parameters of other buttons.

The value returned by Getaxis is 1 to 1

Animator.setfloat (): Set float parameter for Animator

For example, the direction in the blendtree of run can be set by this parameter

Its function signature is public void SetFloat (string name,float value,float damptime,float deltatime);

Name: Names of parameters

Value: Values

Damptime: The time required for the parameter to reach this value

Deltatime: The time consumed by the previous frame

For example:

Animator.setfloat ("Direction", X);

Animator. SetFloat ("Direction", x,0.25f,time.deltatime);

Next put Input.getaxis () and animator. SetFloat () These two interfaces combine to create a script named "Playermanager" that is added to the Player game object

usingUnityengine;usingSystem.Collections; Public classPlayermanager_1:monobehaviour {PrivateAnimator Animator; voidAwake () {animator= getcomponent<animator>(); }    voidUpdate () {//get the value of joystick horizontal axial input        floatH = Input.getaxis ("Horizontal"); //Pass this value to the direction parameter of animatorAnimator. SetFloat ("Direction"H0.25f, Time.deltatime); }}

Run the scene, you can use the keyboard's A/D key or the left arrow right arrow to control the role, you can see the state changes through the animator view

Next we add the (idle) Rest and assign the animation file to the idle bar

The ability to assign speed to speed through the vertical axis in your code

usingUnityengine;usingSystem.Collections; Public classPlayermanager_2:monobehaviour {PrivateAnimator Animator; voidAwake () {animator= getcomponent<animator>(); }    voidUpdate () {//get the value of joystick horizontal axial input        floatv = Input.getaxis ("Vertical"); //get the value of joystick horizontal axial input        floatH = Input.getaxis ("Horizontal"); //Pass this value to the speed parameter of animatorAnimator. SetFloat (" Speed", h*h+v*v); //Pass this value to the direction parameter of animatorAnimator. SetFloat ("Direction"H0.25f, Time.deltatime); }}

Run the game, start the role in the rest state, press w/d not move, because the need to get from the vertical axis speed to switch from the rest to the running state

Finally add the jump state, this example sets the need to move the run-up can be skipped, that is, can not switch from the rest state to the jumping state, only from the running state to jump state

Add the fire button with the following code:

usingUnityengine;usingSystem.Collections; Public classPlayermanager_3:monobehaviour {PrivateAnimator Animator; voidAwake () {//Get animator ComponentsAnimator = getcomponent<animator>(); }    voidUpdate () {//get the value of joystick horizontal axial input            floatv = Input.getaxis ("Vertical"); //get the value of joystick horizontal axial input            floatH = Input.getaxis ("Horizontal"); //Pass this value to the speed parameter of animatorAnimator. SetFloat (" Speed", h*h+v*v); //Pass this value to the direction parameter of animatorAnimator. SetFloat ("Direction"H0.25f, Time.deltatime); //gets the layer with the number 0 in the animator, which is the state information of the base layerAnimatorstateinfo StateInfo = animator. Getcurrentanimatorstateinfo (0); if(Stateinfo.shortnamehash = = Animator.stringtohash ("Run"))            {                //Base layer is run state, set jump to True when the fire button is detected                if(Input.getbutton ("Fire1")) animator. Setbool (" Jump",true); }            Else            {                //set jump to false when base layer is in a different stateAnimator. Setbool (" Jump",false); }    }}

Run the scene, the character can already jump, but there are still two problems

When the character jumps, we look at the scene view and find that the character's body shrinks into a mass when jumping, but the green Collider doesn't change.

Jumped from the platform and did not hit the ground but was back in the running state

Cond............ 2015-11-16

Create a character--03 state machine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.