Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class PlayerController : MonoBehaviour
- {
- // Start is called before the first frame update
- public float speed = 5f;
- public float jumpForce = 1f;
- public float distanceToGround;
- private Rigidbody2D rb;
- private Animator anim;
- private float horizontal;
- private bool facingRight;
- private bool isGrounded = false;
- public Transform groundCheck;
- private float groundRadius = 0.2f;
- public LayerMask whatIsGround;
- void Start()
- {
- //ініціалізація компонентів
- rb = GetComponent<Rigidbody2D>();
- anim = GetComponent<Animator>();
- }
- private void Update()
- {
- if (isGrounded && Input.GetKeyDown(KeyCode.Space))
- {
- anim.SetBool("Ground", false);
- rb.AddForce(new Vector2(0, 100));
- }
- }
- void FixedUpdate()
- {
- isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
- anim.SetBool("Ground", isGrounded);
- anim.SetFloat("jumpForce", rb.velocity.y);
- if (!isGrounded)
- return;
- //вхідні дані про переміщення вліво-вправо
- horizontal = Input.GetAxis("Horizontal");
- //анімація ходьби
- anim.SetFloat("Move", Mathf.Abs(horizontal));
- //перевірка чи персонаж стоїть на землі
- //зміна напрямку персонажа
- if (horizontal > 0 && facingRight || horizontal < 0 && !facingRight)
- Flip();
- //анімація ударів
- if (Input.GetKeyDown(KeyCode.E))
- anim.SetTrigger("Punch");
- if (Input.GetKeyDown(KeyCode.Q))
- anim.SetTrigger("Kick");
- //реалізація стрибку та його анімації
- if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W))
- Jump();
- //анімація приземлення після стрибку
- if (rb.velocity.y < 0)
- anim.SetBool("Jump", false);
- //переміщення персонажа вліво-вправо
- if (horizontal != 0)
- Move();
- }
- private void Jump()
- {
- rb.AddForce(Vector3.up * jumpForce, ForceMode2D.Impulse);
- anim.SetBool("Jump", true);
- }
- private void Move()
- {
- rb.velocity = new Vector3(horizontal * speed, rb.velocity.y);
- Vector3 position = rb.position;
- position.x = Mathf.Clamp(position.x, -5, 6);
- rb.position = position;
- }
- private void Flip()
- {
- facingRight = !facingRight;
- transform.Rotate(0, 180, 0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement