duck

Mecanim Character - Step 4

Feb 27th, 2013
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Character : MonoBehaviour {
  5.  
  6.     public float turnSpeed;
  7.    
  8.     Animator animator;
  9.     Transform look;
  10.    
  11.     bool onGround;
  12.    
  13.     // Use this for initialization
  14.     void Start () {
  15.    
  16.         look = GetComponentInChildren<MouseLookPivot>().transform;
  17.         animator = GetComponentInChildren<Animator>();
  18.        
  19.     }
  20.    
  21.     // Update is called once per frame
  22.     void FixedUpdate () {
  23.    
  24.         bool walk = Input.GetKey(KeyCode.LeftShift);
  25.        
  26.         float v = Input.GetAxis("Vertical");
  27.         float h = Input.GetAxis("Horizontal");
  28.        
  29.         Vector3 move = v * look.forward + h * look.right;      
  30.         Vector3 localMove = transform.InverseTransformDirection(move);
  31.        
  32.         float turn = Mathf.Atan2( localMove.x, localMove.z );
  33.        
  34.         transform.Rotate(0, turn*turnSpeed*Time.deltaTime, 0);
  35.        
  36.         v *= (walk ? 0.5f : 1);
  37.        
  38.         rigidbody.angularVelocity = Vector3.zero;
  39.        
  40.         animator.SetFloat("Forward", localMove.magnitude, 0.1f, Time.deltaTime );
  41.         animator.SetFloat("Turn", turn, 0.1f, Time.deltaTime );
  42.        
  43.         animator.applyRootMotion = onGround;
  44.        
  45.        
  46.         onGround = false;
  47.     }
  48.    
  49.    
  50.     void OnCollisionStay( Collision c )
  51.     {
  52.         foreach ( ContactPoint p in c.contacts )
  53.         {
  54.             Vector3 localP = transform.InverseTransformPoint( p.point );
  55.            
  56.             if (localP.magnitude < (collider as CapsuleCollider).radius)
  57.             {
  58.                 onGround = true;
  59.             }
  60.         }
  61.     }
  62.    
  63.    
  64.     void OnAnimatorIK(int layerIndex)
  65.     {
  66.         animator.SetLookAtWeight(1, 0.2f, 2.5f);
  67.         animator.SetLookAtPosition( look.position + look.forward*10 );
  68.     }
  69.    
  70.    
  71.    
  72. }
Advertisement
Add Comment
Please, Sign In to add comment