duck

Unity 2d character controller using 3d physics

Nov 28th, 2013
572
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.83 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Player : MonoBehaviour {
  5.    
  6.     // place on cube, add a rigidbody, with Freeze Position Z, and Freeze Rotation X,Y,Z
  7.     // use new physic material with zeroed frictions, and friction combine: minimum.
  8.    
  9.     public float moveSpeed = 8;
  10.     public float jumpSpeed = 25;
  11.     public float fallSpeed = 64;
  12.     public float maxFallSpeed = 12;
  13.     public float maxUpSpeed = 25;
  14.    
  15.     Vector3 pos;
  16.     float vm;
  17.     bool onGround;
  18.    
  19.     // Update is called once per frame
  20.     void FixedUpdate () {
  21.    
  22.         pos = transform.position;
  23.         float h = Input.GetAxisRaw("Horizontal");
  24.         float v = Input.GetAxisRaw("Vertical");
  25.         bool jump = Input.GetKey(KeyCode.Space);
  26.        
  27.         if (onGround && jump)
  28.         {
  29.             vm = jumpSpeed;
  30.         }
  31.        
  32.         Vector3 move = new Vector3( -h*moveSpeed, vm, 0 ) * Time.deltaTime;
  33.        
  34.         rigidbody.MovePosition( pos + move );
  35.        
  36.         if (v > 0)
  37.         {
  38.             // jet pack!
  39.             vm += v * Time.deltaTime * 20;
  40.         } else {
  41.             // gravity
  42.             vm -= fallSpeed * Time.deltaTime;
  43.         }
  44.        
  45.         vm = Mathf.Clamp(vm,-maxFallSpeed,maxUpSpeed);
  46.        
  47.         rigidbody.velocity = Vector3.zero;
  48.         onGround = false;
  49.     }
  50.    
  51.    
  52.    
  53.     // ---- Collisions ----
  54.    
  55.     void OnCollisionEnter(Collision c) {
  56.    
  57.         CheckCollision (c);
  58.     }
  59.    
  60.     void OnCollisionStay(Collision c)
  61.     {
  62.         CheckCollision(c); 
  63.     }
  64.      
  65.     void CheckCollision (Collision c)
  66.     {
  67.         foreach (var contact in c.contacts)
  68.         {
  69.             Debug.DrawLine(contact.point, contact.point+contact.normal, Color.red);
  70.            
  71.             // check for floor hit
  72.             if (vm <= 0 && contact.point.y <= collider.bounds.min.y && Vector3.Angle(Vector3.up,contact.normal)<=45)
  73.             {
  74.                 onGround = true;
  75.                 vm = Mathf.Max(0,vm);
  76.             }
  77.            
  78.             // check for head hit:
  79.             if (contact.point.y >= collider.bounds.max.y && Vector3.Angle(-Vector3.up,contact.normal)<=45)
  80.             {
  81.                 vm = Mathf.Min(0,vm);
  82.             }
  83.            
  84.            
  85.         }
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment