Advertisement
duck

Unity C# Rigidbody Character Control With Animation

Oct 1st, 2012
567
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.09 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Player : MonoBehaviour {
  5.  
  6.     public int turnSpeed;
  7.     public int moveSpeed;
  8.     public int jumpForce;
  9.    
  10.     public Animation avatar;
  11.    
  12.     bool onGround;
  13.    
  14.     // Use this for initialization
  15.     void Start () {
  16.    
  17.     }
  18.    
  19.     // Update is called once per frame
  20.     void FixedUpdate () {
  21.    
  22.         float h = Input.GetAxis("Horizontal");
  23.         float v = Input.GetAxis("Vertical");
  24.        
  25.         if (onGround)
  26.         {
  27.             if (v != 0)
  28.             {
  29.                 avatar.CrossFade("run");
  30.             } else {
  31.                 avatar.CrossFade("idle");
  32.             }
  33.         } else {
  34.             avatar.CrossFade("jump");
  35.         }
  36.        
  37.         transform.Rotate( 0, h * turnSpeed * Time.deltaTime, 0 );
  38.         Vector3 moveAmount = transform.forward * v * moveSpeed;
  39.         rigidbody.MovePosition( transform.position + moveAmount * Time.deltaTime );
  40.         rigidbody.velocity = moveAmount + Vector3.Scale(rigidbody.velocity, new Vector3(0,1,0));   
  41.        
  42.         if (onGround && Input.GetKey(KeyCode.Space))
  43.         {
  44.             rigidbody.AddForce( transform.up * jumpForce, ForceMode.Impulse ); 
  45.             onGround = false;
  46.         }
  47.     }
  48.    
  49.     void OnCollisionEnter() {
  50.    
  51.         onGround = true;
  52.        
  53.     }
  54.    
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement