Research on the official self-brought character controller of Unity3d

Source: Internet
Author: User
Tags abs pack lockstate

The official comes with the resource pack first is the download address

5.0.0F4 version of the official own resource pack
Http://pan.baidu.com/s/1o8Ujrxo
2017 stains of the official own resource pack
Http://pan.baidu.com/s/1ge3cUdX
Some will not have to download, if not download download, put in
Under the Xx\editor path, reopen Unity3d to have the import



Assets->standard Assets->characters->firstpersoncharacter->prefabs
Select the precast body and drag it into the scene to use the application

There are two Fpscontroller of precast body

The main components are character controller, script first person controller, Rigidbody
This is the FPS first-person controller, which simulates the way characters move in FPS games, is the first-person controller.
The mouse is locked and the viewing angle moves with the mouse movement. Wsad controlling character movement
Rigidbodyfpscontroller

Main components are capsule Collider, script rigidbody first person Controller
Unlike the Fpscontroller controller, one is to control the movement with Charactercontroller, one is to control the body of the character itself, to add a direction force to the rigid body, you can move
Detailed parsing Scripts First person Controller

Using System;
Using Unityengine;
Using Unitystandardassets.crossplatforminput;
Using Unitystandardassets.utility;

Using Random = Unityengine.random; namespace UnityStandardAssets.Characters.FirstPerson {//Automatically add associated script [Requirecomponent (typeof (Charactercontroller)) ] [Requirecomponent (typeof (Audiosource))] public class Firstpersoncontroller:monobehaviour {//Determine if
        In the walk [Serializefield] private bool m_iswalking;
        Walking speed [Serializefield] private float m_walkspeed;
        The speed of the run [Serializefield] private float m_runspeed;
        Imitate random walking speed [Serializefield] [Range (0f, 1f)] private float m_runsteplenghten;
        Jumping speed [Serializefield] private float m_jumpspeed;
        Judging whether in the air, if a descending force is received in the air [Serializefield] private float m_sticktogroundforce;
        Gravity [Serializefield] private float m_gravitymultiplier;
        Visual angle control script [Serializefield] private mouselook m_mouselook; [SerializEfield] private bool M_usefovkick;
        Fovkick script [Serializefield] private Fovkick M_fovkick = new Fovkick ();
        [Serializefield] private bool m_useheadbob;
        [Serializefield] Private Curvecontrolledbob m_headbob = new Curvecontrolledbob ();
        [Serializefield] Private Lerpcontrolledbob m_jumpbob = new Lerpcontrolledbob ();
        [Serializefield] private float m_stepinterval;    [Serializefield] Private audioclip[] m_footstepsounds;
        An array of footstep sounds, that'll be randomly selected from.           [Serializefield] Private audioclip m_jumpsound;
        The sound played when character leaves the ground.           [Serializefield] Private audioclip m_landsound;

        The sound played is character touches back on ground.
        Private Camera M_camera;
        private bool M_jump;
        private float m_yrotation;
        Private Vector2 M_input;
        Private Vector3 m_movedir = Vector3.zero; Private CharactercontrolLer M_charactercontroller;
        Private Collisionflags m_collisionflags;
        private bool m_previouslygrounded;
        Private Vector3 m_originalcameraposition;
        private float m_stepcycle;
        private float M_nextstep;
        private bool m_jumping;

        Private Audiosource M_audiosource; Use the for initialization private void Start () {M_charactercontroller = getcomponent<
            Charactercontroller> ();
            M_camera = Camera.main;
            M_originalcameraposition = m_Camera.transform.localPosition;
            M_fovkick.setup (M_camera);
            M_headbob.setup (M_camera, m_stepinterval);
            M_stepcycle = 0f;
            M_nextstep = m_stepcycle/2f;
            M_jumping = false;
            M_audiosource = getcomponent<audiosource> ();
        M_mouselook.init (transform, m_camera.transform);
    }//update is called once per frame private void Update () {        Visual angle Control Rotateview ();
            The ' jump ' state needs to read ' to ' make sure it's not missed//goto status judgment if (!m_jump)
            {m_jump = Crossplatforminputmanager.getbuttondown ("Jump");
                }//Determine if on the ground if (!m_previouslygrounded && m_charactercontroller.isgrounded) {
                Startcoroutine (M_jumpbob.dobobcycle ());
                Playlandingsound ();
                M_movedir.y = 0f;
            M_jumping = false; }//Not on the ground and not in the jumping state if (!m_charactercontroller.isgrounded &&!m_jumping && M_previo
            uslygrounded) {m_movedir.y = 0f;
        } m_previouslygrounded = m_charactercontroller.isgrounded;
            }//Play landed sound private void Playlandingsound () {m_audiosource.clip = M_landsound;
            M_audiosource.play ();M_nextstep = M_stepcycle +. 5f;
            }//control character Walk private void Fixedupdate () {float speed;
            GetInput (out speed);
            Always move along the camera forward as it's the direction that it being aimed at//keeps moving forward along the camera as it is aimed in the direction

            Vector3 desiredmove = Transform.forward*m_input.y + transform.right*m_input.x; Get a normal for the surface it's being touched to move along it//get a regular surface and be touched to move it raycasth
            It hitinfo;
                               Physics.spherecast (Transform.position, M_charactercontroller.radius, Vector3.down, out HitInfo,
            M_CHARACTERCONTROLLER.HEIGHT/2F);

            Desiredmove = Vector3.projectonplane (Desiredmove, hitinfo.normal). normalized;
            m_movedir.x = Desiredmove.x*speed;


            M_movedir.z = Desiredmove.z*speed; if (m_charactercontroller.isgrounded) {m_movedir.y =-m_sticktogRoundforce;
                    if (m_jump) {m_movedir.y = M_jumpspeed;
                    Playjumpsound ();
                    M_jump = false;
                M_jumping = true; }} else {m_movedir + = physics.gravity*m_gravitymultiplier*time.fixed
            Deltatime;

            } m_collisionflags = M_charactercontroller.move (m_movedir*time.fixeddeltatime);
            Progressstepcycle (speed);
        Updatecameraposition (speed);
            }//Play the Jumping Sound private void playjumpsound () {m_audiosource.clip = M_jumpsound;
        M_audiosource.play (); } private void Progressstepcycle (float speed) {if (m_CharacterController.velocity.sqrMagnit Ude > 0 && (m_input.x! = 0 | | M_input.y! = 0)) {m_stepcycle + = (m_charactercontrol Ler.velocity.magnitude + (speed* (M_iswalkiNg?
            1f:m_runsteplenghten))) * TIME.FIXEDDELTATIME; } if (! (
            M_stepcycle > M_nextstep) {return;

            } m_nextstep = m_stepcycle + m_stepinterval;
        Playfootstepaudio (); 
            }//Play script sound private void Playfootstepaudio () {if (!m_charactercontroller.isgrounded)
            {return;
            }//Pick & play a random footstep sound from the array,//excluding sound at index 0
            int n = random.range (1, m_footstepsounds.length);
            M_audiosource.clip = M_footstepsounds[n];
            M_audiosource.playoneshot (M_audiosource.clip);
            Move picked sound to index 0 so it's not picked next time m_footstepsounds[n] = m_footstepsounds[0];
        M_footstepsounds[0] = M_audiosource.clip; }//control camera's viewing angle move private void UpdatecAmeraposition (float speed) {Vector3 newcameraposition;
            if (!m_useheadbob) {return;
            } if (M_CharacterController.velocity.magnitude > 0 && m_charactercontroller.isgrounded) {m_Camera.transform.localPosition = M_headbob.doheadbob (m_charactercontroller.veloci
                Ty.magnitude + (speed* (m_iswalking? 1f:m_runsteplenghten)));
                Newcameraposition = m_Camera.transform.localPosition;
            NEWCAMERAPOSITION.Y = M_camera.transform.localposition.y-m_jumpbob.offset ();
                } else {newcameraposition = m_Camera.transform.localPosition;
            NEWCAMERAPOSITION.Y = M_originalcameraposition.y-m_jumpbob.offset ();
        } m_Camera.transform.localPosition = Newcameraposition; }//Get keyboard input private void GEtinput (out float speed) {//Read input Float horizontal = Crossplatforminputmanager.geta
            XIs ("horizontal");

            float vertical = Crossplatforminputmanager.getaxis ("vertical");

bool waswalking = m_iswalking; #if!
            Mobile_input//On standalone builds, Walk/run speed was modified by a key press. Keep track of whether or isn't the character is walking or running m_iswalking =!
Input.getkey (Keycode.leftshift); #endif//Set the desired speed to being walking or running speed = m_iswalking?
            M_walkspeed:m_runspeed;

            M_input = new Vector2 (horizontal, vertical);
                Normalize input if it exceeds 1 in combined length:if (M_input.sqrmagnitude > 1) {
            M_input.normalize (); }//handle speed give a FOV kick//If the player is going to a run, is running and the FovkickIS-to-be used if (m_iswalking! = waswalking && m_usefovkick && m_charactercontroller.velocity.
                Sqrmagnitude > 0) {stopallcoroutines ();
            Startcoroutine (!m_iswalking m_fovkick.fovkickup (): M_fovkick.fovkickdown ()); }}//select Perspective to normal angle private void Rotateview () {m_mouselook.lookrotation (TRANSFO
        RM, M_camera.transform); }//Controller collision Response private void Oncontrollercolliderhit (Controllercolliderhit hit) {rigidbo
            DY BODY = hit.collider.attachedRigidbody;
            Dont move the rigidbody if the character is on top of it if (m_collisionflags = = Collisionflags.below)
            {return;
            } if (BODY = = NULL | | body.iskinematic) {return; } body. Addforceatposition (m_charactercontroller.velocity*0.1f, Hit.point, forcemode.iMpulse);
 }
    }
}

The main characters Move code

M_collisionflags = M_charactercontroller.move (m_movedir*time.fixeddeltatime);


M_collisionflags Collision Detection Flag M_charactercontroller the
Charactercontroller component of the role
M_movedir the current direction of movement multiplied by the input obtained by the keyboard
time.fixeddeltatime Fixed time increment

If you want to remove the mouse lock, you can modify the mouselook in this script

Update the mouse-locked state of public
void Updatecursorlock ()
        {
            //if the user set "Lockcursor" we check & properly lock the Cursos
            if (lockcursor)
                internallockupdate ();
        }
        Control mouse lock
        private void Internallockupdate ()
        {
            if (Input.getkeyup (keycode.escape))
            {
                m_ cursorislocked = false;
            }
            else if (Input.getmousebuttonup (1))
            {
                m_cursorislocked = true;
            }

            if (m_cursorislocked)
            {
                cursor.lockstate = cursorlockmode.locked;
                Cursor.visible = false;
            }
            else if (!m_cursorislocked)
            {
                cursor.lockstate = Cursorlockmode.none;
                Cursor.visible = true;
            }
        }
Rigidbodyfirstpersoncontroller
Using System;
Using Unityengine;

Using Unitystandardassets.crossplatforminput; namespace UnityStandardAssets.Characters.FirstPerson {//Automatically add associated script [Requirecomponent (typeof (Rigidbody))] [Req Uirecomponent (typeof (Capsulecollider))] public class Rigidbodyfirstpersoncontroller:monobehaviour {[Se Rializable] public class Movementsettings {//forward speed public float forwardspeed = 8.0   F  Speed when walking forward//back to public float backwardspeed = 4.0f;    When walking backwards//walk speed horizontal public float strafespeed = 4.0f;   Speed when walking sideways//run of public float runmultiplier = 2.0f;
            Speed when sprinting//Run key set to Leftshift public keycode runkey = Keycode.leftshift;
            Jumping force public float jumpforce = 30f; Animation curve, used in the model animation playback of the collision box scaling and gravity adjustment public Animationcurve SlopeCurvemodifier = new Animationcurve (New Keyframe ( -90.0f, 1.0f), New Keyframe (0.0f, 1.0f), New Keyframe (90.0f, 0.0f));

Current target speed [hideininspector] public float currenttargetspeed = 8f; #if!
Mobile_input private bool m_running;
                #endif//update required target speed public void updatedesiredtargetspeed (Vector2 input) {
                if (input = = Vector2.zero) return; if (Input.x > 0 | | input.x < 0) {//strafe currenttargetspee
                D = strafespeed; } if (Input.y < 0) {//backwards currenttargets
                peed = Backwardspeed; } if (Input.y > 0) {//forwards//handled last As if strafing and moving forward at the same time forwards speed should take precedence Currenttarget Speed = forwardspeed; } #if! Mobile_input if (Input.getkey (Runkey)) {currenttargetspeed *= Runmult
                    Iplier;
                M_running = true;
                } else {m_running = false; } #endif} #if!
            Mobile_input public bool Running {get {return m_running;} } #endif}//Advanced settings [Serializable] public class Advancedsettings {//check The distance the controller is grounded (0.01f seems to be most suitable for this) public float groundcheckdistance = 0.01f;
            Distance for checking if the controller was grounded (0.01f seems to work best for this)//stop this role public float sticktogroundhelperdistance = 0.5f; Stops the character//when there is no input, the controller reaches the stop speed public float slowdownrate = 20f; Rate at which-the controller comes to a stop-there is No input//user can control the direction of movement in the air, public bool Aircontrol;
        Can the user control the direction that's being moved in the air} public Camera cam;
        Public movementsettings movementsettings = new Movementsettings ();
        Public Mouselook mouselook = new Mouselook ();


        Public advancedsettings advancedsettings = new Advancedsettings ();
        Private Rigidbody m_rigidbody;
        Private Capsulecollider M_capsule;
        private float m_yrotation;
        Private Vector3 M_groundcontactnormal;


        private bool M_jump, m_previouslygrounded, m_jumping, m_isgrounded;
        Public Vector3 Velocity {get {return m_rigidbody.velocity;}
        } public bool Grounded {get {return m_isgrounded;}
        } public bool Jumping {get {return m_jumping;} } public bool Running {get {#if!
Mobile_input                return movementsettings.running;
#else return false; #endif}} private void Start () {m_rigidbody = Getcomponent<rigidbod
            Y> ();
            M_capsule = getcomponent<capsulecollider> ();
        Mouselook.init (transform, cam.transform);
            } private void Update () {//control angle of rotation to normal position rotateview ();
                Leap State judgment Transfer if (Crossplatforminputmanager.getbuttondown ("Jump") &&!m_jump) {
            M_jump = true; }}//Move function private void fixedupdate () {//To determine the distance between the bottom and the ground Groundcheck (
            );
            Vector2 input = GetInput (); If the keyboard is detected with input if (Mathf.abs (input.x) > float. Epsilon | | Mathf.abs (INPUT.Y) > float. Epsilon) && (Advancedsettings.aircontrol | | m_isgrounded)) {// Always move along the camera forward as it is the direction so it being aimed at//keeps moving forward along the camera as it is aimed at the side
                to Vector3 desiredmove = Cam.transform.forward*input.y + cam.transform.right*input.x;

                Desiredmove = Vector3.projectonplane (Desiredmove, m_groundcontactnormal). normalized;
                desiredmove.x = Desiredmove.x*movementsettings.currenttargetspeed; Desiredmov

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.