duck

Unity 2D Platformer Simple Arcade Player Control

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