Advertisement
Guest User

Untitled

a guest
Nov 19th, 2019
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.80 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class PlayerController : MonoBehaviour
  6. {
  7. // Start is called before the first frame update
  8. public float speed = 5f;
  9. public float jumpForce = 1f;
  10. public float distanceToGround;
  11. private Rigidbody2D rb;
  12. private Animator anim;
  13. private float horizontal;
  14. private bool facingRight;
  15.  
  16. private bool isGrounded = false;
  17.  
  18. public Transform groundCheck;
  19.  
  20. private float groundRadius = 0.2f;
  21. public LayerMask whatIsGround;
  22. void Start()
  23. {
  24. //ініціалізація компонентів
  25. rb = GetComponent<Rigidbody2D>();
  26. anim = GetComponent<Animator>();
  27. }
  28.  
  29. private void Update()
  30. {
  31. if (isGrounded && Input.GetKeyDown(KeyCode.Space))
  32. {
  33. anim.SetBool("Ground", false);
  34. rb.AddForce(new Vector2(0, 100));
  35. }
  36. }
  37. void FixedUpdate()
  38. {
  39. isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
  40. anim.SetBool("Ground", isGrounded);
  41. anim.SetFloat("jumpForce", rb.velocity.y);
  42. if (!isGrounded)
  43. return;
  44.  
  45. //вхідні дані про переміщення вліво-вправо
  46. horizontal = Input.GetAxis("Horizontal");
  47. //анімація ходьби
  48. anim.SetFloat("Move", Mathf.Abs(horizontal));
  49. //перевірка чи персонаж стоїть на землі
  50. //зміна напрямку персонажа
  51. if (horizontal > 0 && facingRight || horizontal < 0 && !facingRight)
  52. Flip();
  53. //анімація ударів
  54. if (Input.GetKeyDown(KeyCode.E))
  55. anim.SetTrigger("Punch");
  56. if (Input.GetKeyDown(KeyCode.Q))
  57. anim.SetTrigger("Kick");
  58. //реалізація стрибку та його анімації
  59. if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W))
  60. Jump();
  61. //анімація приземлення після стрибку
  62. if (rb.velocity.y < 0)
  63. anim.SetBool("Jump", false);
  64. //переміщення персонажа вліво-вправо
  65. if (horizontal != 0)
  66. Move();
  67. }
  68. private void Jump()
  69. {
  70. rb.AddForce(Vector3.up * jumpForce, ForceMode2D.Impulse);
  71. anim.SetBool("Jump", true);
  72. }
  73. private void Move()
  74. {
  75. rb.velocity = new Vector3(horizontal * speed, rb.velocity.y);
  76. Vector3 position = rb.position;
  77. position.x = Mathf.Clamp(position.x, -5, 6);
  78. rb.position = position;
  79. }
  80. private void Flip()
  81. {
  82. facingRight = !facingRight;
  83. transform.Rotate(0, 180, 0);
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement