Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. public class PlayerBehaviour : MonoBehaviour
  2. {
  3. // Variable set for calculation in update
  4.  
  5. // Max speed, in units per second, that the character moves.
  6. float speed = 9;
  7. // Acceleration while grounded
  8. float walkAcceleration = 75;
  9. // Deceleration applied when character is grounded and not attempting to move
  10. float groundDeceleration = 70;
  11. // Max height the character will jump regardless of gravity
  12. float jumpHeight = 7;
  13.  
  14.  
  15. // Main Unity Physics ref
  16. private Vector2 velocity;
  17. private Rigidbody2D rb;
  18.  
  19. // Additional ref
  20. private BoxCollider2D boxCollider;
  21.  
  22. // State for checking
  23. public enum State
  24. {
  25. Ground = 0,
  26. Jump = 1,
  27. Fall = 2,
  28. }
  29.  
  30. private State state = State.Ground;
  31.  
  32. private void Start()
  33. {
  34. rb = GetComponent<Rigidbody2D>();
  35. }
  36. // Update is called once per frame
  37. void Update()
  38. {
  39. float moveInput = Input.GetAxisRaw("Horizontal");
  40. velocity.x = Mathf.MoveTowards(velocity.x, speed * moveInput, walkAcceleration * Time.deltaTime);
  41.  
  42. transform.Translate(velocity * Time.deltaTime);
  43.  
  44. if (moveInput != 0)
  45. {
  46. velocity.x = Mathf.MoveTowards(velocity.x, speed * moveInput, walkAcceleration * Time.deltaTime);
  47. }
  48. else
  49. {
  50. velocity.x = Mathf.MoveTowards(velocity.x, 0, groundDeceleration * Time.deltaTime);
  51. }
  52.  
  53. Vector2 ve = rb.velocity;
  54. if (state == State.Ground && Input.GetButtonDown("Jump"))
  55. {
  56. ve.y = jumpHeight;
  57. }
  58. ve.x = 0;
  59. rb.velocity = ve;
  60. }
  61.  
  62. void FixedUpdate()
  63. {
  64. //CameraWork goes here if nessary
  65. }
  66.  
  67. void OnCollisionEnter2D(Collision2D collision)
  68. {
  69. if (collision.gameObject.tag == "Platform")
  70. {
  71. state = State.Ground;
  72. velocity.y = 0;
  73. }
  74. }
  75. void OnCollisionExit2D(Collision2D collision)
  76. {
  77. if (collision.gameObject.tag == "Platform")
  78. {
  79. if (state == State.Ground)
  80. {
  81. state = State.Fall;
  82. }
  83. }
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement