Advertisement
Guest User

2DPlayerCharacter

a guest
May 21st, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class 2DPlayerController : MonoBehaviour
  6. {
  7. [SerializeField] private float speed = 40f;
  8. [SerializeField] private float jumpForce = 8f;
  9. [SerializeField] private float jumpTime = 0.35f;
  10. [SerializeField] private float doubleJumpTime = 0.15f;
  11. [SerializeField] private int maxJumps = 2;
  12.  
  13. [SerializeField] public Transform groundCheck;
  14. [SerializeField] public LayerMask whatIsGround;
  15.  
  16. private float moveInput;
  17. private float jumpTimeCounter;
  18. private int remainingJumps;
  19. private bool toJump;
  20.  
  21. private Rigidbody2D rbody;
  22.  
  23. private void Awake() {
  24. rbody = GetComponent<Rigidbody2D>();
  25. }
  26.  
  27. private void Update() {
  28. moveInput = Input.GetAxisRaw("Horizontal");
  29.  
  30. if (moveInput > 0) {
  31. transform.eulerAngles = new Vector3(0, 0, 0);
  32. }
  33. else if (moveInput < 0) {
  34. transform.eulerAngles = new Vector3(0, 180, 0);
  35. }
  36.  
  37. if (Input.GetButtonDown("Jump")) {
  38. if (remainingJumps == maxJumps) {
  39. jumpTimeCounter = jumpTime;
  40. }
  41. else {
  42. jumpTimeCounter = doubleJumpTime;
  43. }
  44. remainingJumps--;
  45. }
  46.  
  47. if (Input.GetButton("Jump") && remainingJumps > -1) {
  48. if (jumpTimeCounter > 0) {
  49. toJump = true;
  50. jumpTimeCounter -= Time.deltaTime;
  51. }
  52. }
  53. else {
  54. Collider2D[] colliders = Physics2D.OverlapBoxAll(groundCheck.position, new Vector3(0.9f, 0.1f, 0), whatIsGround);
  55. for (int i = 0; i < colliders.Length; i++) {
  56. if (colliders[i].gameObject != gameObject) {
  57. remainingJumps = maxJumps;
  58. }
  59. }
  60. }
  61. }
  62.  
  63. private void FixedUpdate() {
  64. rbody.velocity = new Vector2(moveInput * speed, rbody.velocity.y);
  65.  
  66. if (toJump) {
  67. rbody.velocity = new Vector2(rbody.velocity.x, jumpForce);
  68. toJump = false;
  69. }
  70. }
  71.  
  72. private void OnDrawGizmos() {
  73. Gizmos.DrawCube(groundCheck.position, new Vector3(0.9f, 0.1f, 0));
  74. Gizmos.color = Color.red;
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement