Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class PlayerMovement : MonoBehaviour {
- // Debugging
- public bool loggingEnabled = false;
- // Keycodes
- public KeyCode moveLeft = KeyCode.A;
- public KeyCode moveRight = KeyCode.D;
- public KeyCode jump = KeyCode.Space;
- public KeyCode altMoveLeft = KeyCode.LeftArrow;
- public KeyCode altMoveRight = KeyCode.RightArrow;
- public KeyCode altJump = KeyCode.Z;
- // Physics
- public float acceleration = 10;
- public float jumpForce = 200;
- public float maxSpeed = 10;
- private Vector2 moveDir = Vector2.zero;
- // By doing this, isGrounded becomes read-only outside of this script
- [HideInInspector] public bool isGrounded { get; private set; }
- // Initialization
- void Start ()
- {
- isGrounded = false;
- }
- void FixedUpdate ()
- {
- moveDir = Vector2.zero;
- if (isGrounded)
- {
- if (Input.GetKey (jump) || Input.GetKey (altJump) && rigidbody2D.velocity.y < 10)
- moveDir.y += jumpForce;
- }
- if (Input.GetKey (moveLeft) || Input.GetKey (altMoveLeft))
- {
- moveDir.x -= acceleration;
- }
- if (Input.GetKey (moveRight) || Input.GetKey (altMoveRight))
- {
- moveDir.x += acceleration;
- }
- rigidbody2D.AddForce (moveDir);
- Vector2 velocity = rigidbody2D.velocity;
- velocity.x = Mathf.Clamp (velocity.x, -maxSpeed, maxSpeed);
- rigidbody2D.velocity = velocity;
- if (loggingEnabled)
- Debug.Log (isGrounded + " " + transform.position + " | " + moveDir);
- }
- // Thanks to Thenewbloods for the info
- void OnTriggerStay2D (Collider2D other)
- {
- if (other.tag == "Ground" && isGrounded == false)
- isGrounded = true;
- }
- void OnTriggerExit2D (Collider2D other)
- {
- if (other.tag == "Ground")
- isGrounded = false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement