shadowx320

Player.cs

Sep 27th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. [RequireComponent(typeof(Controller2D))]
  5. public class Player : MonoBehaviour
  6. {
  7.  
  8. public float jumpHeight = 4;
  9. public float timeToJumpApex = .4f;
  10. float accelerationTimeAirborne = .2f;
  11. float accelerationTimeGrounded = .1f;
  12. float moveSpeed = 6;
  13.  
  14. float gravity;
  15. float jumpVelocity;
  16. Vector3 velocity;
  17. float velocityXSmoothing;
  18.  
  19. Controller2D controller;
  20.  
  21. void Start()
  22. {
  23. controller = GetComponent<Controller2D>();
  24.  
  25. gravity = -(2 * jumpHeight) / Mathf.Pow(timeToJumpApex, 2);
  26. jumpVelocity = Mathf.Abs(gravity) * timeToJumpApex;
  27. print("Gravity: " + gravity + " Jump Velocity: " + jumpVelocity);
  28. }
  29.  
  30. void Update()
  31. {
  32.  
  33. if (controller.collisions.above || controller.collisions.below)
  34. {
  35. velocity.y = 0;
  36. }
  37.  
  38. Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
  39.  
  40. if (Input.GetKeyDown(KeyCode.Space) && controller.collisions.below)
  41. {
  42. velocity.y = jumpVelocity;
  43. }
  44.  
  45. float targetVelocityX = input.x * moveSpeed;
  46. velocity.x = Mathf.SmoothDamp(velocity.x, targetVelocityX, ref velocityXSmoothing, (controller.collisions.below) ? accelerationTimeGrounded : accelerationTimeAirborne);
  47. velocity.y += gravity * Time.deltaTime;
  48. controller.Move(velocity * Time.deltaTime);
  49. }
  50. }
Add Comment
Please, Sign In to add comment