Search Unity

rigidbody controller

Discussion in 'Scripting' started by jaasso, Oct 4, 2015.

  1. jaasso

    jaasso

    Joined:
    Jun 19, 2013
    Posts:
    64
    these buttons are required in project input settings

    Forward
    Back
    Left
    Right
    Run
    Jump
    LookAround
    ToggleCrouch
    Mouse X
    Mouse Y

    attach to a capsule and set camera that is its child in the inspector

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. [RequireComponent(typeof(CapsuleCollider))]
    5. [RequireComponent(typeof(Rigidbody))]
    6.  
    7. public class Rbctrl : MonoBehaviour
    8. {
    9.     CapsuleCollider capsCollider;
    10.     float crouchHeight,standHeight;
    11.    
    12.     Rigidbody rb;
    13.    
    14.     public Transform cam;
    15.     public bool invertY;
    16.    
    17.     public float acceleration=6,deceleration=6,maxForwardSpeed=22,maxBackSpeed=18,maxStrafeSpeed=18,runModifier=18,crouchModifier=.6f,
    18.    
    19.     rotSpeed=4,minRotX=-90,maxRotX=90,minRotY=-90,maxRotY=90,
    20.    
    21.     rigidbodyDrag=5, speedMultiplierX=1,speedMultiplierZ=1,
    22.    
    23.     minJumpPower=9,maxJumpPower=9,
    24.     jumpMultiplierX=.01f,jumpMultiplierY=.6f,jumpMultiplierZ=.01f,
    25.    
    26.     groundCheckDistance = .1f,
    27.     stickToGroundHelperDistance=.05f,
    28.    
    29.     camBobX=.006f,camBobY=.008f,camBobZ=0,camReturnSpeed=.04f,
    30.    
    31.     playStepSoundAmount=666;
    32.    
    33.     public AudioClip[] stepSounds;
    34.     public AudioClip[] jumpSounds;
    35.     public AudioClip[] landSounds;
    36.    
    37.     AudioSource stepSourceA,stepSourceB,jumpSource,landSource;
    38.    
    39.     float currentAcceleration,currentDeceleration,currentMaxForwardSpeed,currentMaxBackSpeed,currentMaxStrafeSpeed,currentRunModifier,
    40.    
    41.     currentSpeedZ,currentSpeedX,speedBoost,
    42.    
    43.     rotationY,
    44.    
    45.     jumpPower,jumpZ,jumpX,
    46.    
    47.     addedJumpX,addedJumpZ,
    48.    
    49.     stepSoundAmount,stepVolume,
    50.    
    51.     camRotX,camRotY,previousCamRotX,
    52.    
    53.     camX,camY,camZ,camBobSpeed,
    54.    
    55.     n0,n1,combinedSpeeds,camSlerpAmount;
    56.    
    57.     int randomStepSoundIndex,lastStepIndex,randomLandSoundIndex,randomJumpSoundIndex;
    58.    
    59.     bool grounded,lookingAround,stepToggle,crouching,jumping;
    60.    
    61.     Quaternion camStartRot;
    62.     Vector3 camTargetPosLocal,camStandTargetPos,camCrouchTargetPos;
    63.    
    64.     void Start ()
    65.     {
    66.         capsCollider=GetComponent<CapsuleCollider>();
    67.        
    68.         PhysicMaterial mat=new PhysicMaterial();
    69.         mat.dynamicFriction=0;
    70.         mat.staticFriction=1;
    71.        
    72.         capsCollider.material=mat;
    73.        
    74.         rb = GetComponent<Rigidbody>();
    75.         rb.constraints=RigidbodyConstraints.FreezeRotation;
    76.         rb.collisionDetectionMode=CollisionDetectionMode.ContinuousDynamic;
    77.        
    78.         crouchHeight=capsCollider.bounds.size.y*.66f;
    79.         standHeight=capsCollider.bounds.size.y;
    80.        
    81.         camStandTargetPos=cam.localPosition;
    82.         camCrouchTargetPos=new Vector3(camStandTargetPos.x,camStandTargetPos.y*.6f,camStandTargetPos.z);
    83.         camTargetPosLocal=camStandTargetPos;
    84.         camY=camTargetPosLocal.y;
    85.         camX=camTargetPosLocal.x;
    86.         camZ=camTargetPosLocal.z;
    87.         camBobSpeed=(camBobX+camBobY+camBobZ)*1.1f;
    88.        
    89.         currentAcceleration= acceleration;
    90.         currentDeceleration=deceleration;
    91.         currentMaxForwardSpeed =maxForwardSpeed;
    92.         currentMaxStrafeSpeed =maxStrafeSpeed;
    93.         currentMaxBackSpeed= maxBackSpeed;
    94.         currentRunModifier= runModifier;
    95.        
    96.         n0 = (maxStrafeSpeed+maxBackSpeed+maxForwardSpeed)/3;
    97.         n1=n0+runModifier;
    98.        
    99.         stepSourceA=gameObject.AddComponent<AudioSource>();
    100.         stepSourceB=gameObject.AddComponent<AudioSource>();
    101.         jumpSource=gameObject.AddComponent<AudioSource>();
    102.         landSource=gameObject.AddComponent<AudioSource>();
    103.     }
    104.    
    105.     void Update()
    106.     {
    107.         if(Input.GetButtonDown ("ToggleCrouch"))
    108.         {
    109.             crouching=!crouching;
    110.            
    111.             if(crouching)
    112.             {
    113.                 capsCollider.height=crouchHeight;
    114.                
    115.                 camTargetPosLocal=camCrouchTargetPos;
    116.                
    117.                 camX=camTargetPosLocal.x;
    118.                 camY=camTargetPosLocal.y;
    119.                 camZ=camTargetPosLocal.z;
    120.                
    121.                 currentAcceleration*=crouchModifier;
    122.                 currentDeceleration*=crouchModifier;
    123.                 currentMaxBackSpeed*=crouchModifier;
    124.                 currentMaxForwardSpeed*=crouchModifier;
    125.                 currentMaxStrafeSpeed*=crouchModifier;
    126.                 currentRunModifier*=crouchModifier;
    127.             }
    128.             else
    129.             {
    130.                 capsCollider.height=standHeight;
    131.                
    132.                 camTargetPosLocal=camStandTargetPos;
    133.                
    134.                 camX=camTargetPosLocal.x;
    135.                 camY=camTargetPosLocal.y;
    136.                 camZ=camTargetPosLocal.z;
    137.                
    138.                 currentAcceleration=acceleration;
    139.                 currentDeceleration=deceleration;
    140.                 currentMaxBackSpeed=maxBackSpeed;
    141.                 currentMaxForwardSpeed=maxForwardSpeed;
    142.                 currentMaxStrafeSpeed=maxStrafeSpeed;
    143.                 currentRunModifier=runModifier;
    144.             }
    145.         }
    146.        
    147.         if(!lookingAround)
    148.         {
    149.             if(invertY)
    150.             {
    151.                 camRotX += Input.GetAxisRaw ("Mouse Y")*rotSpeed;
    152.             }
    153.             else
    154.             {
    155.                 camRotX -= Input.GetAxisRaw ("Mouse Y")*rotSpeed;
    156.             }
    157.            
    158.             camRotX = Mathf.Clamp (camRotX, minRotX,maxRotX);
    159.            
    160.             cam.localRotation=Quaternion.Euler (camRotX,0,0);
    161.            
    162.             if(Input.GetButtonDown ("LookAround"))
    163.             {
    164.                 previousCamRotX=camRotX;
    165.                 lookingAround=true;
    166.                
    167.                 cam.localPosition=camTargetPosLocal;
    168.             }
    169.         }
    170.         else
    171.         {
    172.             if(Input.GetButtonUp ("LookAround"))
    173.             {
    174.                 camStartRot = cam.localRotation;
    175.                 StartCoroutine ("ReturnCamRot");
    176.             }
    177.             camRotY+=Input.GetAxisRaw ("Mouse X")*rotSpeed;
    178.             camRotY = Mathf.Clamp (camRotY,minRotY,maxRotY);
    179.            
    180.             if(invertY)
    181.             {
    182.                 camRotX += Input.GetAxisRaw ("Mouse Y")*rotSpeed;
    183.             }
    184.             else
    185.             {
    186.                 camRotX -= Input.GetAxisRaw ("Mouse Y")*rotSpeed;
    187.             }
    188.            
    189.             camRotX = Mathf.Clamp (camRotX, minRotX,maxRotX);
    190.            
    191.             cam.localRotation=Quaternion.Euler (camRotX,camRotY,0);
    192.         }
    193.        
    194.         if(Input.GetButton ("Jump"))
    195.         {
    196.             jumpPower+=currentAcceleration;
    197.            
    198.             if(Input.GetButton ("Forward"))
    199.                 jumpZ+=currentAcceleration;
    200.             if(Input.GetButton ("Back"))
    201.                 jumpZ-=currentAcceleration;
    202.             if(Input.GetButton ("Left"))
    203.                 jumpX-=currentAcceleration;
    204.             if(Input.GetButton ("Right"))
    205.                 jumpX+=currentAcceleration;
    206.         }
    207.        
    208.         if(Input.GetButtonUp ("Forward"))
    209.             if(!Input.GetButton ("Back"))
    210.                 StartCoroutine ("SlowDownZ");
    211.         if(Input.GetButtonUp ("Back"))
    212.             if(!Input.GetButton ("Forward"))
    213.                 StartCoroutine ("SlowDownZ");
    214.        
    215.         if(Input.GetButtonUp ("Left"))
    216.             if(!Input.GetButton ("Right"))
    217.                 StartCoroutine ("SlowDownX");
    218.         if(Input.GetButtonUp ("Right"))
    219.             if(!Input.GetButton ("Left"))
    220.                 StartCoroutine ("SlowDownX");
    221.        
    222.         if(Input.GetButtonUp ("Jump"))
    223.         {
    224.             if(grounded)
    225.             {
    226.                 jumpZ = Mathf.Clamp (jumpZ,-maxJumpPower,maxJumpPower);
    227.                 jumpX = Mathf.Clamp (jumpX,-maxJumpPower,maxJumpPower);
    228.                
    229.                 addedJumpX = jumpX + currentSpeedX;
    230.                 addedJumpZ = jumpZ + currentSpeedZ;
    231.                
    232.                 jumpPower = Mathf.Clamp (jumpPower,minJumpPower,maxJumpPower);
    233.                
    234.                 rb.AddRelativeForce (addedJumpX*jumpMultiplierX, jumpPower*jumpMultiplierY,addedJumpZ*jumpMultiplierZ,ForceMode.Impulse);
    235.                
    236.                 if(jumpSounds.Length>0)
    237.                 {
    238.                     randomJumpSoundIndex=Random.Range (0,jumpSounds.Length);
    239.                    
    240.                     jumpSource.clip=jumpSounds[randomJumpSoundIndex];
    241.                     jumpSource.volume=Random.Range (.5f,1f);
    242.                     jumpSource.Play ();
    243.                 }
    244.                
    245.                 stepSoundAmount=0;
    246.                 StopCoroutine ("SlowDownX");
    247.                 StopCoroutine ("SlowDownZ");
    248.                 currentSpeedZ=0;
    249.                 currentSpeedX=0;
    250.                
    251.                 jumping=true;
    252.             }
    253.             jumpPower = 0;
    254.             jumpX = 0;
    255.             jumpZ = 0;
    256.         }
    257.        
    258.         if(grounded)
    259.         {
    260.             rotationY=Input.GetAxis ("Mouse X");
    261.            
    262.             if(Input.GetButtonDown ("Forward") || Input.GetButtonDown ("Back"))
    263.             {
    264.                 StopCoroutine ("SlowDownZ");
    265.             }
    266.             if(Input.GetButtonDown ("Left") || Input.GetButtonDown ("Right"))
    267.             {
    268.                 StopCoroutine ("SlowDownX");
    269.             }
    270.            
    271.             if(Input.GetButton ("Forward"))
    272.             {
    273.                 currentSpeedZ+=currentAcceleration;
    274.             }
    275.             if(Input.GetButton ("Back"))
    276.             {
    277.                 currentSpeedZ-=currentAcceleration;
    278.             }
    279.             if(Input.GetButton ("Left"))
    280.             {
    281.                 currentSpeedX-=currentAcceleration;
    282.             }
    283.             if(Input.GetButton ("Right"))
    284.             {
    285.                 currentSpeedX+=currentAcceleration;
    286.             }
    287.            
    288.             if(Input.GetButton ("Run"))
    289.             {
    290.                 speedBoost+=currentAcceleration;
    291.             }
    292.             else
    293.             {
    294.                 speedBoost-=currentDeceleration;
    295.             }
    296.            
    297.             speedBoost = Mathf.Clamp (speedBoost,0,runModifier);
    298.            
    299.             currentSpeedZ = Mathf.Clamp (currentSpeedZ,-currentMaxBackSpeed-speedBoost,currentMaxForwardSpeed+speedBoost);
    300.             currentSpeedX = Mathf.Clamp (currentSpeedX,-currentMaxStrafeSpeed-speedBoost,currentMaxStrafeSpeed+speedBoost);
    301.         }
    302.     }
    303.    
    304.     IEnumerator SlowDownZ()
    305.     {
    306.         while(true)
    307.         {
    308.             currentSpeedZ+=currentSpeedZ>0 ? -deceleration:deceleration;
    309.            
    310.             if(Mathf.Abs (currentSpeedZ)<=deceleration)
    311.             {
    312.                 currentSpeedZ=0;
    313.                 yield break;
    314.             }
    315.             else
    316.             {
    317.                 yield return null;
    318.             }
    319.         }
    320.     }
    321.     IEnumerator SlowDownX()
    322.     {
    323.         while(true)
    324.         {
    325.             currentSpeedX+=currentSpeedX>0 ? -deceleration:deceleration;
    326.            
    327.             if(Mathf.Abs (currentSpeedX)<=deceleration)
    328.             {
    329.                 currentSpeedX=0;
    330.                 yield break;
    331.             }
    332.             else
    333.             {
    334.                 yield return null;
    335.             }
    336.         }
    337.     }
    338.    
    339.     IEnumerator ReturnCamRot()
    340.     {
    341.         while(true)
    342.         {
    343.             camSlerpAmount+=camReturnSpeed;
    344.             cam.localRotation =  Quaternion.Slerp (camStartRot,Quaternion.Euler (previousCamRotX,0,0),camSlerpAmount);
    345.            
    346.             if(camSlerpAmount>.99f)
    347.             {
    348.                 camSlerpAmount = 0;
    349.                 camRotY = 0;
    350.                 camRotX=previousCamRotX;
    351.                 cam.localRotation = Quaternion.Euler (camRotX,0,0);
    352.                
    353.                 cam.localPosition=camTargetPosLocal;
    354.                 camY=camTargetPosLocal.y;
    355.                 camX=camTargetPosLocal.x;
    356.                 camZ=camTargetPosLocal.z;
    357.                
    358.                 lookingAround=false;
    359.                
    360.                 yield break;
    361.             }
    362.            
    363.             yield return null;
    364.         }
    365.     }
    366.    
    367.     Quaternion deltaRotation;
    368.    
    369.     void FixedUpdate()
    370.     {
    371.         GroundCheck();
    372.        
    373.         if(grounded)
    374.         {
    375.             rb.AddRelativeForce (currentSpeedX*speedMultiplierX,0,currentSpeedZ*speedMultiplierZ);
    376.            
    377.             if(!lookingAround)
    378.             {
    379.                 deltaRotation = Quaternion.Euler(new Vector3(0,rotationY*rotSpeed,0));
    380.                 transform.rotation=transform.rotation*deltaRotation;
    381.             }
    382.            
    383.             if(currentSpeedX==0&&currentSpeedZ==0)
    384.             {
    385.                 cam.localPosition=Vector3.MoveTowards (cam.localPosition,camTargetPosLocal,camBobSpeed);
    386.             }
    387.            
    388.             combinedSpeeds=Mathf.Abs (currentSpeedZ) + Mathf.Abs (currentSpeedX);
    389.            
    390.             if(currentSpeedX != 0 && currentSpeedZ != 0)
    391.             {
    392.                 stepSoundAmount+=combinedSpeeds*.5f*
    393.                     Mathf.Clamp ( Mathf.Abs (transform.InverseTransformDirection (rb.velocity).z)+
    394.                                  Mathf.Abs (transform.InverseTransformDirection (rb.velocity).x),0,1) ;
    395.             }
    396.             else
    397.             {
    398.                 stepSoundAmount+=combinedSpeeds*
    399.                     Mathf.Clamp ( Mathf.Abs (transform.InverseTransformDirection (rb.velocity).z)+
    400.                                  Mathf.Abs (transform.InverseTransformDirection (rb.velocity).x),0,1) ;
    401.             }
    402.            
    403.             if(!lookingAround)
    404.             {
    405.                 if(stepSoundAmount>playStepSoundAmount*.5f)
    406.                 {
    407.                     camY-=camBobY;
    408.                     camZ+=camBobZ;
    409.                    
    410.                     camX += stepToggle ? -camBobX : camBobX;
    411.                    
    412.                     cam.localPosition=Vector3.MoveTowards (cam.localPosition,new Vector3(camX,camY,camZ),camBobSpeed*
    413.                                                            Mathf.Clamp ( Mathf.Abs (transform.InverseTransformDirection (rb.velocity).z)+
    414.                                  Mathf.Abs (transform.InverseTransformDirection (rb.velocity).x),0,1));
    415.                 }
    416.                 else if(stepSoundAmount>playStepSoundAmount*.2f)
    417.                 {
    418.                     cam.localPosition=Vector3.MoveTowards (cam.localPosition,camTargetPosLocal,camBobSpeed*1.45f);
    419.                 }
    420.             }
    421.            
    422.             if(stepSoundAmount>playStepSoundAmount)
    423.             {
    424.                 stepToggle=!stepToggle;
    425.                
    426.                 camY=camTargetPosLocal.y;
    427.                 camX=camTargetPosLocal.x;
    428.                 camZ=camTargetPosLocal.z;
    429.                
    430.                 if(stepSounds.Length>0)
    431.                 {
    432.                     if(stepSounds.Length>1)
    433.                     {
    434.                         for(int i=0;i<Mathf.Infinity;i++)
    435.                         {
    436.                             randomStepSoundIndex=Random.Range (0,stepSounds.Length);
    437.                            
    438.                             if(randomStepSoundIndex!=lastStepIndex)
    439.                                 break;
    440.                         }
    441.                     }
    442.                    
    443.                     if(currentSpeedX != 0 && currentSpeedZ != 0)
    444.                     {
    445.                         stepVolume = ((float)Mathf.Abs (currentSpeedX)/n1+(float)Mathf.Abs (currentSpeedZ)/n1)*.5f;
    446.                     }
    447.                     else
    448.                     {
    449.                         stepVolume = ((float)Mathf.Abs (currentSpeedX)/n1+(float)Mathf.Abs (currentSpeedZ)/n1);
    450.                     }
    451.                    
    452.                     stepVolume=Mathf.Clamp (stepVolume,0,1);
    453.                    
    454.                     if(stepToggle)
    455.                     {
    456.                         stepSourceA.clip=stepSounds[randomStepSoundIndex];
    457.                         stepSourceA.volume=stepVolume;
    458.                         stepSourceA.Play ();
    459.                     }
    460.                     else
    461.                     {
    462.                         stepSourceB.clip=stepSounds[randomStepSoundIndex];
    463.                         stepSourceB.volume=stepVolume;
    464.                         stepSourceB.Play ();
    465.                     }
    466.                    
    467.                     lastStepIndex=randomStepSoundIndex;
    468.                 }
    469.                
    470.                 stepSoundAmount=0;
    471.             }
    472.            
    473.         }
    474.        
    475.         StickToGroundHelper ();
    476.     }
    477.    
    478.     RaycastHit hitInfo;
    479.    
    480.     bool previouslyGrounded;
    481.    
    482.     void GroundCheck()
    483.     {
    484.         if (Physics.SphereCast(transform.position, capsCollider.radius-.01f, Vector3.down, out hitInfo,
    485.                                ((capsCollider.height/2f) - capsCollider.radius) + groundCheckDistance))
    486.         {
    487.             rb.drag=rigidbodyDrag;
    488.            
    489.             grounded = true;
    490.            
    491.             if(!previouslyGrounded&&jumping)
    492.             {
    493.                 if(landSounds.Length>0)
    494.                 {
    495.                     if(!landSource.isPlaying)
    496.                     {
    497.                         randomLandSoundIndex=Random.Range (0,landSounds.Length);
    498.                        
    499.                         landSource.clip=landSounds[randomLandSoundIndex];
    500.                         landSource.volume=Random.Range (.5f,1f);
    501.                         landSource.Play ();
    502.                     }
    503.                 }
    504.                
    505.                 jumping=false;
    506.             }
    507.         }
    508.         else
    509.         {
    510.             rb.drag=0;
    511.            
    512.             grounded = false;
    513.         }
    514.        
    515.         previouslyGrounded=grounded;
    516.     }
    517.    
    518.     void StickToGroundHelper()
    519.     {
    520.         if (Physics.SphereCast(transform.position, capsCollider.radius-.01f, Vector3.down, out hitInfo,
    521.                                ((capsCollider.height/2f) - capsCollider.radius) +
    522.                                stickToGroundHelperDistance))
    523.         {
    524.             if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f)
    525.             {
    526.                 rb.velocity = Vector3.ProjectOnPlane(rb.velocity, hitInfo.normal);
    527.             }
    528.         }
    529.     }
    530. }
     
    Last edited: May 9, 2016
  2. jaasso

    jaasso

    Joined:
    Jun 19, 2013
    Posts:
    64
    revised it quite a bit
     
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532
    How about a description as to what this is, how it works, why you posted it here (and edited it 6 months later).

    What's up?
     
    jaasso likes this.
  4. jaasso

    jaasso

    Joined:
    Jun 19, 2013
    Posts:
    64
    it's a rigidbody first person controller that i left here in case someone finds a use for it