Advertisement
rdgorodrigo

Untitled

Jul 4th, 2020
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Movement : MonoBehaviour
  6. {
  7. [Header("Movement")]
  8. public float speed;
  9. Rigidbody2D body;
  10. Vector2 mov;
  11. public bool FacingRight = true;
  12. public bool canMov = true;
  13.  
  14. [Header("Jump")]
  15. public float jumpForce;
  16. public bool grounded = false;
  17. public Transform groundCheck;
  18. private float nextJump = 0.5f;
  19. public float extraJump = 0;
  20.  
  21. [Header("Input")]
  22. float moveHorizontal;
  23.  
  24. [Header("Animation")]
  25. Animator anim;
  26.  
  27. void Start()
  28. {
  29. body = GetComponent<Rigidbody2D>();
  30. anim = GetComponent<Animator>();
  31. }
  32.  
  33. // Update is called once per frame
  34. void Update()
  35. {
  36. if (canMov)
  37. {
  38. moveHorizontal = Input.GetAxis("Horizontal");
  39.  
  40. grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
  41. Debug.DrawLine(transform.position, groundCheck.position, Color.green);
  42.  
  43. if (Input.GetButtonDown("Jump") && grounded)
  44. {
  45. if (Time.time > nextJump)
  46. {
  47. nextJump = Time.time + 0.5f;
  48. StartCoroutine(Jump());
  49. }
  50. }
  51. if (Input.GetButton("Jump") && !grounded)
  52. {
  53. extraJump += Time.deltaTime * jumpForce * 50;
  54. }
  55. else
  56. {
  57. extraJump = 0;
  58. }
  59. }
  60. }
  61.  
  62. void FixedUpdate()
  63. {
  64. if (canMov)
  65. {
  66. Move();
  67. }
  68. }
  69.  
  70. void Move()
  71. {
  72. mov = new Vector2(moveHorizontal * speed, body.velocity.y);
  73. body.velocity = mov;
  74.  
  75. //FacingParameters
  76. if (moveHorizontal > 0 && !FacingRight)
  77. {
  78. Flip();
  79. }
  80. else if (moveHorizontal < 0 && FacingRight)
  81. {
  82. Flip();
  83. }
  84.  
  85. //AnimParameters
  86. if (moveHorizontal != 0)
  87. AnimHorizontal();
  88.  
  89. }
  90.  
  91. IEnumerator Jump()
  92. {
  93. body.AddForce(new Vector2(0, jumpForce),ForceMode2D.Impulse);
  94. float elapsedTime = 0;
  95. while (elapsedTime < 0.18f)
  96. {
  97. elapsedTime += Time.deltaTime;
  98. body.AddForce(new Vector2(0, extraJump), ForceMode2D.Force);
  99. yield return new WaitForSeconds(0);
  100. }
  101. }
  102.  
  103.  
  104. public void Flip()
  105. {
  106. FacingRight = !FacingRight;
  107. Vector3 X_Scale = transform.localScale;
  108. X_Scale.x *= -1;
  109. transform.localScale = X_Scale;
  110. }
  111.  
  112. void AnimHorizontal()
  113. {
  114. anim.SetFloat("Walk", Mathf.Abs(moveHorizontal));
  115. }
  116. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement