duck

Unity 3d Simple Mecanim Character Script

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