Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class PlayerMove : MonoBehaviour {
- //Ustawienia ruchu
- public float movementSpeed;
- public float jumpForce;
- public bool allowMovementInAir;
- //Krzywa, która opisuje zmianę prędkości ruchu w zależności od nachylenia podłoża. Jeżeli idziemy pod górkę kąt jest >90stopni
- //Z górki <90 stopni.
- public AnimationCurve slopeCurveModifier;
- //Wewnętrzne zmienne
- private Rigidbody rb;
- private Vector3 groundContactNormal;
- [SerializeField]
- private bool isGrounded, previouslyGrounded, jumping;
- void Start () {
- rb = GetComponent<Rigidbody>();
- }
- void Update () {
- GroundCheck();
- rb.drag = isGrounded ? 5f : 0f;
- Vector2 movementInput = GetMovementInput();
- Vector3 forwardMovement = transform.forward * movementInput.y;
- Vector3 sideMovement = transform.right * movementInput.x;
- if (isGrounded || allowMovementInAir)
- {
- //Dodajemy wyliczoną siłę wynikającą z inputu i mnożymy ją razy mnożnik z konta z podłożem oraz prędkość ruchu.
- rb.AddForce((forwardMovement + sideMovement) * movementSpeed * SlopeMultiplier());
- }
- if (Input.GetButtonDown("Jump") && isGrounded && !jumping)
- {
- rb.AddForce(new Vector3(0f, jumpForce, 0f));
- jumping = true;
- }
- }
- Vector2 GetMovementInput()
- {
- float x = Input.GetAxis("Horizontal");
- float y = Input.GetAxis("Vertical");
- return new Vector2(x, y);
- }
- private float SlopeMultiplier()
- {
- //Liczymy kąt pomiędzy graczem a podłożem - na tej podstawie wyliczamy mnożnik prędkości ruchu
- float angle = Vector3.Angle(groundContactNormal, transform.forward);
- return slopeCurveModifier.Evaluate(angle);
- }
- private void GroundCheck()
- {
- RaycastHit hitInfo;
- previouslyGrounded = isGrounded;
- //Raycast do wyszukiwania podłoża na którym stoimy
- if(Physics.SphereCast(transform.position,
- GetComponent<CapsuleCollider>().radius,
- Vector3.down,
- out hitInfo,
- 1.02f,
- Physics.AllLayers,
- QueryTriggerInteraction.Ignore))
- {
- //Jeżeli na czymś stoimy ustawiamy isGrounded i pobieramy wektor normalny podłoża (wytłumaczyć dzieciom co to normalna)
- isGrounded = true;
- groundContactNormal = hitInfo.normal;
- }
- else
- {
- //W przeciwnym wypadku resetujemy isGrounded i ustawiamy normalną podłoża na wektor skierowany w górę
- isGrounded = false;
- groundContactNormal = Vector3.up;
- }
- //Czy zakończyliśmy skok?
- if (!previouslyGrounded && isGrounded && jumping)
- {
- jumping = false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement