Advertisement
Guest User

PlayerMovement.cs

a guest
Aug 22nd, 2014
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.73 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class PlayerMovement : MonoBehaviour {
  5.  
  6.     // Debugging
  7.     public bool loggingEnabled = false;
  8.  
  9.     // Keycodes
  10.     public KeyCode moveLeft = KeyCode.A;
  11.     public KeyCode moveRight = KeyCode.D;
  12.     public KeyCode jump = KeyCode.Space;
  13.    
  14.     public KeyCode altMoveLeft = KeyCode.LeftArrow;
  15.     public KeyCode altMoveRight = KeyCode.RightArrow;
  16.     public KeyCode altJump = KeyCode.Z;
  17.    
  18.     // Physics
  19.     public float acceleration = 10;
  20.     public float jumpForce = 200;
  21.     public float maxSpeed = 10;
  22.  
  23.     private Vector2 moveDir = Vector2.zero;
  24.     // By doing this, isGrounded becomes read-only outside of this script
  25.     [HideInInspector] public bool isGrounded { get; private set; }
  26.  
  27.     // Initialization
  28.     void Start ()
  29.     {
  30.         isGrounded = false;
  31.     }
  32.  
  33.     void FixedUpdate ()
  34.     {
  35.         moveDir = Vector2.zero;
  36.  
  37.         if (isGrounded)
  38.         {
  39.             if (Input.GetKey (jump) || Input.GetKey (altJump) && rigidbody2D.velocity.y < 10)
  40.                 moveDir.y += jumpForce;
  41.         }
  42.        
  43.         if (Input.GetKey (moveLeft) || Input.GetKey (altMoveLeft))
  44.         {
  45.             moveDir.x -= acceleration;
  46.         }
  47.        
  48.         if (Input.GetKey (moveRight) || Input.GetKey (altMoveRight))
  49.         {
  50.             moveDir.x += acceleration;
  51.         }
  52.        
  53.         rigidbody2D.AddForce (moveDir);
  54.  
  55.         Vector2 velocity = rigidbody2D.velocity;
  56.         velocity.x = Mathf.Clamp (velocity.x, -maxSpeed, maxSpeed);
  57.         rigidbody2D.velocity = velocity;
  58.  
  59.         if (loggingEnabled)
  60.             Debug.Log (isGrounded + " " + transform.position + " | " + moveDir);
  61.     }
  62.  
  63.     // Thanks to Thenewbloods for the info
  64.     void OnTriggerStay2D (Collider2D other)
  65.     {
  66.         if (other.tag == "Ground" && isGrounded == false)
  67.             isGrounded = true;
  68.     }
  69.    
  70.     void OnTriggerExit2D (Collider2D other)
  71.     {
  72.         if (other.tag == "Ground")
  73.             isGrounded = false;
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement