This article mainly talk about what to control move and rotate the player and simulate the gravity by using Charactercontro Ller component.
Now we add a component.just seems like this.
We set the values to fit the scene,and now we gonna do the next.
We attach a new C # script named Charactercontrol
This is the code.
1 usingUnityengine;2 usingSystem.Collections;3 4 Public classCharactercontrolscript:monobehaviour5 {6 //Control Speed7 Public floatMovespeed =10.0f;8 Public floatRotatespeed =1.0f;9 Public floatJumpspeed =4.0f;// The speed of the jumpTen Public floatGravity =1;//The gravity One A Private BOOLIsmainplayer =false; - PrivateAnimator Personanimator; - PrivateCharactercontroller cc; the - Public BOOLIsjump; - Private BOOLIsmove; - + Privatecollisionflags flags; - + PrivateVector3 movedirection; A at - //Use this for initialization - voidStart () - { - if( This. Gameobject.tag = ="Player") - { inIsmainplayer =true; -CC = This. Getcomponent<charactercontroller>(); to } +Personanimator = gameobject.getcomponent<animator>(); - } the * //Update is called once per frame $ voidUpdate ()Panax Notoginseng { - //if the object of the current script is a player the if(Ismainplayer) + { A //Press Arrow keys tp move or rotate the floatH = Input.getaxis ("Horizontal"); + floatv = Input.getaxis ("Vertical"); -H *= Time.deltatime *Movespeed; $V *= time.deltatime *Movespeed; $Transform. Translate (H,0, v); -Transform. Rotate (0, H * rotatespeed,0); - the //FIX This bug:can not move backwards! Its animation only has the forward one - if(Mathf.abs (Input.getaxis ("Vertical")) >0.1f)Wuyi { thePersonanimator.setfloat ("Speed_f", movespeed); - } Wu - Else About { $Personanimator.setfloat ("Speed_f",0); - } - - A + the //Press space key to jump - //Here is 2 types of jump ways:standing Jumpand running jump $ if(Input.getkeydown (keycode.space) &&!isjump) the { thePersonanimator.setbool ("jump_b",true); the theIsjump =true; -Movedirection =transform. Transformdirection (movedirection); inMOVEDIRECTION.Y =Jumpspeed; the the } About Else if(Input.getkeyup (keycode.space)) the { thePersonanimator.setbool ("jump_b",false); the } + - //if (isjump) the ///{Bayi //simulate the Fall physic theMOVEDIRECTION.Y-= Gravity *Time.deltatime; theFlags = CC. Move (Movedirection *time.deltatime); - - //When hit the ground the if(Flags = =Collisionflags.below) the { theIsjump =false; the } - // } the } the the }94}
Now we can control the player by press arrow buttons and space to jump.
[Unity3d] How to control your player to move and rotate by using Charactercontroller